2个双数之间的随机数 [英] Random Number Between 2 Double Numbers

查看:21
本文介绍了2个双数之间的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 2 个双打之间生成一个随机数?

Is it possible to generate a random number between 2 doubles?

示例:

public double GetRandomeNumber(double minimum, double maximum)
{
    return Random.NextDouble(minimum, maximum) 
}

然后我用以下代码调用它:

Then I call it with the following:

double result = GetRandomNumber(1.23, 5.34);

如有任何想法,我们将不胜感激.

Any thoughts would be appreciated.

推荐答案

是.

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.

这篇关于2个双数之间的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆