你如何生成在C#中的随机数? [英] How do you generate a random number in C#?
问题描述
我想生成两个值之间的随机浮点数。什么是C#做到这一点的最好方法是什么?
I would like to generate a random floating point number between 2 values. What is the best way to do this in C#?
推荐答案
我想加入的的埃里克响应的说明;我觉得为什么代码工作,知识比知道什么代码工作更好
The only thing I'd add to Eric's response is an explanation; I feel that knowledge of why code works is better than knowing what code works.
的解释是这样的:假设你想在2.5和4.5之间的数字。的范围是2.0(4.5 - 2.5)。 NextDouble
只返回一个0到1.0之间的数字,但如果你的范围内乘这个,你会得到0和范围的之间的一个数字。
The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). NextDouble
only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and range.
那么,这会给我们随机双打0.0到2.0之间:
So, this would give us random doubles between 0.0 and 2.0:
rng.NextDouble() * 2.0
不过,我们希望他们在2.5和4.5之间!我们如何做到这一点?添加的最小数字,2.5:
But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:
2.5 + rng.NextDouble() * 2.0
现在,我们得到了0.0和2.0之间的数字;如果添加2.5到每一个值,我们看到现在的范围是2.5到4.5之间。
Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.
起初我以为这要紧,如果B> A或A> b,但是如果你工作了两种方式,你会发现它的作品了相同的,只要你不乱时使用的变量的顺序。我想用较长的变量名称来表达它,所以我没有得到混合起来:
At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:
double NextDouble(Random rng, double min, double max)
{
return min + (rng.NextDouble() * (max - min));
}
这篇关于你如何生成在C#中的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!