且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

2个双数之间的随机数

更新时间:2023-02-10 12:10:18

是.

Random.NextDouble 返回一个介于 0 和 1 之间的双精度值.然后将其乘以需要进入的范围(最大值和最小值之间的差值),然后将其添加到基数(最小值)中.

Random.NextDouble returns a double between 0 and 1. You then multiply that by the range you need to go into (difference between maximum and minimum) and then add that to the base (minimum).

public double GetRandomNumber(double minimum, double maximum)
{ 
    Random random = new Random();
    return random.NextDouble() * (maximum - minimum) + minimum;
}

真正的代码应该有 random 是一个静态成员.这将节省创建随机数生成器的成本,并使您能够非常频繁地调用 GetRandomNumber.由于我们在每次调用时都初始化一个新的 RNG,如果您调用的速度足够快,系统时间不会在两次调用之间发生变化,那么 RNG 将使用完全相同的时间戳进行播种,并生成相同的随机数流.

Real code should have random be a static member. This will save the cost of creating the random number generator, and will enable you to call GetRandomNumber very frequently. Since we are initializing a new RNG with every call, if you call quick enough that the system time doesn't change between calls the RNG will get seeded with the exact same timestamp, and generate the same stream of random numbers.