DayTwo
DayTwo

Reputation: 759

Why does System.Random always return the same number?

Using System.Random the below always returns 0. I need a random number between 0 and 1. It always returns 0 I would expect some distribution O's and 1's. Thanks

Random random = new Random();

int randomInt = random.Next(0, 1)

Upvotes: 1

Views: 926

Answers (5)

basti
basti

Reputation: 2689

Try

Random random = new Random();

int randomInt = random.Next(0, 2)

The Max-Value will not be reached...

Upvotes: 5

Pabuc
Pabuc

Reputation: 5638

try random.NextDouble(). There is no int between 0 and 1.

Upvotes: 0

Cheng Chen
Cheng Chen

Reputation: 43513

Random.Next will return an int, that's why you always get 0. Use Random.NextDouble instead.

Upvotes: 2

Colin Mackay
Colin Mackay

Reputation: 19175

See the documentation for this method: http://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx

The number range returned will be from zero to zero. Greater or equal to the first value and less than the second value.

Upvotes: 3

MatthiasG
MatthiasG

Reputation: 4532

The upper bound is exclusive and won't be reached.

Upvotes: 2

Related Questions