如何在C#中生成随机整数?


当前回答

Random类用于创建随机数。(当然是伪随机)。

例子:

Random rnd = new Random();
int month  = rnd.Next(1, 13);  // creates a number between 1 and 12
int dice   = rnd.Next(1, 7);   // creates a number between 1 and 6
int card   = rnd.Next(52);     // creates a number between 0 and 51

如果您要创建多个随机数,则应保留random实例并重复使用。如果您创建的新实例时间太近,它们将生成与随机生成器从系统时钟中生成的序列相同的随机数。

其他回答

如果您希望CSRNG生成最小值和最大值之间的随机数,这是适合您的。它将使用安全的随机种子初始化随机类。

    class SecureRandom : Random
    {
        public static byte[] GetBytes(ulong length)
        {
            RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
            byte[] bytes = new byte[length];
            RNG.GetBytes(bytes);
            RNG.Dispose();
            return bytes;
        }
        public SecureRandom() : base(BitConverter.ToInt32(GetBytes(4), 0))
        {

        }
        public int GetRandomInt(int min, int max)
        {
            int treashold = max - min;
            if(treashold != Math.Abs(treashold))
            {
                throw new ArithmeticException("The minimum value can't exceed the maximum value!");
            }
            if (treashold == 0)
            {
                throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
            }
            return min + (Next() % treashold);
        }
        public static int GetRandomIntStatic(int min, int max)
        {
            int treashold = max - min;
            if (treashold != Math.Abs(treashold))
            {
                throw new ArithmeticException("The minimum value can't exceed the maximum value!");
            }
            if(treashold == 0)
            {
                throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
            }
            return min + (BitConverter.ToInt32(GetBytes(4), 0) % treashold);
        }
    }

内置Random类(System.Random)生成的数字生成伪随机数。

如果你想要真正的随机数,我们最接近的就是“安全伪随机生成器”,它可以通过使用C#中的Cryptographic类(如RNGCryptoServiceProvider)生成。

即使如此,如果你仍然需要真正的随机数,你将需要使用一个外部源,比如解释放射性衰变的设备,作为随机数发生器的种子。因为,根据定义,任何纯算法产生的数字都不可能是真正随机的。

 int n = new Random().Next();

您还可以为Next()函数指定最小值和最大值。喜欢:

 int n = new Random().Next(5, 10);

虽然这还可以:

Random random = new Random();
int randomNumber = random.Next()

大多数情况下,您需要控制限制(最小和最大数量)。因此,您需要指定随机数的开始和结束位置。

Next()方法接受两个参数,min和max。

所以,如果我希望我的随机数介于5和15之间,我就这么做

int randomNumber = random.Next(5, 16)
Random r=new Random();
int Numbers=r.next(min value, max value);