6
votes

I am writing a random question generator. I would like to pick one question from each section.

Random class with DateTime.Now.Milliseconds as seed value generates random numbers, if the range is greater than 2(0,2/2+). But, If I give a min of 0 and a max of 1 in the range, it always returns me 0.

Am I using it wrongly.

Please suggest if there are any other alternatives.

Thanks, Mahesh

3

3 Answers

17
votes

You're calling Random.Next, which returns a random integer more than or equal to the first parameter and less than, but not equal to, the second.
Specifically, you're asking for an integer in the range [0, 1), which can only be zero.

If you're looking for an integer that is either 0 or 1, you need to call Random.Next(0, 2).

If you're looking for a real number between 0 and 1, you need to call Random.NextDouble.

0
votes

Reading on MSDN (Random.Next(int), Random.Next(int, int)) you will see that the upper bound is always exclusive. That is, to get a number between 0 and 1 (both inclusive) you can do:

Random prng = new Random();
Console.WriteLine(prng.Next(0, 2)); //2 because it is exclusive
0
votes

MSDN: Random.Next Method (Int32) Returns a nonnegative random number less than the specified maximum. Use this.

Random random = new Random();

for (int i = 0; i < 10; i++)
{
  Console.WriteLine("Genereted value:{0}", random.Next(2));
}