Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

random

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

like image 472
Mahesh Avatar asked Nov 30 '10 12:11

Mahesh


People also ask

Does random next include 0?

Random. Next generates a random number whose value ranges from 0 to less than Int32. MaxValue. To generate a random number whose value ranges from 0 to some other positive number, use the Random.

How does random in C# work?

Examples to Implement C# random Then the main method is called within which an instance of the Random class is created to be able to make use of the Next() method. Then the Next() method is called to generate a random integer value between −2,147,483,648 and +2,147,483,648 and stored in an integer variable.

What is seed in random C#?

Seed Int32. A number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used.


1 Answers

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.

like image 109
SLaks Avatar answered Sep 28 '22 19:09

SLaks