开发者

.NET Random Class picking always 0 when range is 0 or 1

开发者 https://www.devze.com 2023-01-27 19:59 出处:网络
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 gre

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


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.


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


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));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号