Random.Next always returns the same values.

I use the method to generate a unique number, but always get the same number -2147483648. Even if I stop the program, recompile it and run it again, I still see the same number.

  public static int GetRandomInt(int length)
    {           
        var min = Math.Pow(10, length - 1);
        var max = Math.Pow(10, length) - 1;
        var random = new Random();
        return random.Next((int)min, (int)max);
    }
+3
source share
9 answers

You have three problems with your code.

  • You must exteriorize your random variable.
  • You have a problem with a truncation error.
  • The range between min and max is large.

, . ( b ) ints. , - . min max ( ) 1- > 20:

length  max-min        
1       8
2       89
3       899
4       8999
5       89999
6       899999
7       8999999
8       89999999
9       899999999
10      8,999,999,999
11      89999999999
12      899999999999
13      8999999999999
14      89999999999999
15      899999999999999
16      9E+15
17      9E+16
18      9E+17
19      9E+18

, 2 147 483 647, , 9.

+2

:

private readonly Random _random = new Random();

public static int GetRandomInt(int length)
{           
    var min = Math.Pow(10, length - 1);
    var max = Math.Pow(10, length) - 1;
    return _random.Next((int)min, (int)max);
}
+7

, , , , - (2 ^ 32)

, int. :

        var min = Math.Pow(10, length - 1);
        var max = Math.Pow(10, length) - 1;
        var random = new Random();
        var a = (int)min;
        var b = (int)max;
        return random.Next(a, b);

, a b - -2147483648, Next(min, max) (doc , min == max, return min).

, , 9. 10 System.ArgumentOutOfRangeException, > 10 -2147483648.

+3

Random not new() , .

, . .

+2

, min max. , Int32.MaxValue ...

+1

Random, :

public class MyClass
{
private readonly Random random = new Random();

public static int GetRandomInt(int length)
{
  var min = Math.Pow(10, length - 1);
  var max = Math.Pow(10, length) - 1;
  return random.Next((int)min, (int)max);
}

}

, , .

0

, :

  • Random()
  • , , , .

. ( , , , ...).

0

Random , . , RNG . Random ( ), , , , , .

Remember that an RNG initialized with seed A will always return the sequence B. Therefore, if you create three instances Random, all seeded ones, for example 123, these three instances will always return the same number at the same iteration.

0
source

All Articles