Reputation: 65
I have this:
int minValue = int.Parse(min.Text);
int maxValue = int.Parse(max.Text);
Random rnd = new Random();
int final = rnd.Next(minValue, maxValue);
result.Text = final.ToString("");
I'm going to get the two values (lower value and higher value) to two textboxes. These values are entered by the user. When I generate the random number, in no situation does the higher value appear. For example, the user enters 1 and 5. I repeatedly generate a number and in no situation does the number 5 appear. It only appears either 1, or 2, or 3, or 4, not 5. Why?
Upvotes: 0
Views: 207
Reputation: 23
int minValue = int.Parse(min.Text);
int maxValue = int.Parse(max.Text)+1;
Random rnd = new Random();
int final = rnd.Next(minValue, maxValue);
result.Text = final.ToString("");
This will work because when it takes maxvalue range starts from minValue to maxValue-1.
Upvotes: 1
Reputation: 2930
If you look at function docs: https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx
The higher value is exclusive.
To include it you need to do :
int final = rnd.Next(minValue, maxValue+1);
Upvotes: 6
Reputation: 9679
Because Random.Next gives random value exclusive upper bound.
https://msdn.microsoft.com/library/2dx6wyd4(v=vs.110).aspx
Upvotes: 8