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


当前回答

根据定义,由计算机通过确定性过程计算的数字不能是随机的。

如果你想要一个真正的随机数,随机性来自大气噪声或放射性衰变。

例如,您可以尝试RANDOM.ORG(它会降低性能)

其他回答

尝试以下简单步骤创建随机数:

创建函数:

private int randomnumber(int min, int max)
{
    Random rnum = new Random();
    return rnum.Next(min, max);
}

在要使用随机数的位置使用上述函数。假设您想在文本框中使用它。

textBox1.Text = randomnumber(0, 999).ToString();

0是最小值,999是最大值。您可以将值更改为任意值。

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

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

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

对于强随机种子,我总是使用CryptoRNG而不是时间。

using System;
using System.Security.Cryptography;

public class Program
{
    public static void Main()
    {
        var random = new Random(GetSeed());
        Console.WriteLine(random.Next());
    }

    public static int GetSeed() 
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var intBytes = new byte[4];
            rng.GetBytes(intBytes);
            return BitConverter.ToInt32(intBytes, 0);
        }
    }
}

有许多实用程序函数或服务以与System.Random相同的方式更好地缓存,因此它适合于通用实现:

static public class CachedService<T> where T : new() {
    static public T Get { get; } = new T();
}

用于随机(或类似):

CachedService<System.Random>.Get.Next(999);
Random rand = new Random();
int name = rand.Next()

在第二个括号中放入所需的值确保通过编写prop和double tab来设置名称以生成代码