C # random - if the operator is only output = -1

I'm trying to make my program output 1 or -1, this is my code, and its only output is -1. This is not random at all.

Random rnd = new Random(); int L = rnd.Next(0, 1); if (L == 0) { Console.WriteLine(-1); } else { Console.WriteLine(1); } 
+6
source share
4 answers

The second argument, Random.Next(int, int) gives an exclusive upper bound. Thus, you say that you want the integer to be greater than or equal to 0 and less than 1. This does not provide many possibilities 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 is equal to maxValue, minValue is returned.

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

+12
source

rnd.Next(0, 1) returns the value of i in the range 0 <= i < 1 . The only such value is 0 .

Take a look at the documentation :

Minvalue

Type: System.Int32

An inclusive lower bound for a random number is obtained.

Maxvalue

Type: System.Int32

The exceptional upper bound of the random number is back. maxValue must be greater than or equal to minValue.

Please note that minValue is inclusive and maxValue is exclusive. Thus, in more general terms, this overload of next() returns values ​​in the range:

 minValue <= i < maxValue 

If you do not know the terminology, in the context of inequalities inclusive means <= or >= and exceptional means < or > .

Well, the above inequality is not strictly true in the case of minValue == maxValue, but I prefer to neglect this corner case for a cleaner presentation.

+7
source

Random.Next with 2 arguments returns min <= <max

so you need the values ​​0 or 1, just change the code to: rnd.Next(0, 2); - this will return either 0 or 1

0
source

I'm trying to make my program output 1 or -1, this is my code, and its only output is -1. This is not random at all.

Instead, you can use a simple algorithm:

 int L = (rnd.Next (1, 3) * 2) - 3; Console.WriteLine(L); 
0
source

Source: https://habr.com/ru/post/957626/


All Articles