Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# random - if statement only output = -1

Tags:

c#

random

I'm trying to make my program output either 1 or -1 this is my code so far and its only output is -1. It's not random at all.

Random rnd = new Random();
int L = rnd.Next(0, 1);
if (L == 0)
{
    Console.WriteLine(-1);
}
else
{
    Console.WriteLine(1);
}
like image 808
Paludan Avatar asked Nov 07 '13 20:11

Paludan


1 Answers

The second argument Random.Next(int, int) gives an exclusive upper bound. So you're saying you want an integer greater than or equal to 0, and less than 1. That doesn't give a lot of scope for numbers other than 0 :)

From the documentation:

Return Value
Type: System.Int32
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

You should also read my article on randomness to avoid other common problems.

like image 148
Jon Skeet Avatar answered Sep 20 '22 10:09

Jon Skeet