C ++随机数生成 [英] C++ random number generation
问题描述
例如,以下表达式:
r = (rand() % 10)+1;
从1-10
生成一个随机数.
如何使它从0-10
生成随机数?
How can we make it generate random numbers from 0-10
?
谢谢.
推荐答案
您快到了! rand()
函数返回一个相当大范围(0到RAND_MAX
)的随机值.使用模数运算符可以将此范围缩小到一个较小的范围(从0到9,因为您要乘以10),然后+1将此范围从1移到10.
You're almost there! The rand()
function returns a random value in a pretty large range (0 to RAND_MAX
). The use of the modulus operator wraps this down into a smaller range (from 0 to 9, since you're modding by 10) and then the +1 moves this to be from 1 to 10.
要获取0到10之间的值,可以使用rand
并将其值修改为11:
To get values between 0 and 10, you can take rand
and mod its value by 11:
r = rand() % 11;
通常,要获得[0,n]范围内的随机值,您可以编写
More generally, to get random values in the range [0, n], you can write
r = rand() % (n + 1);
最后,要获得[k,n + k]范围内的值,您可以编写
And finally, to get values in the range [k, n + k], you can write
r = rand() % (n + 1) + k;
当然,正如纯粹主义者指出的那样,这不一定会给您真正统一的值,因为将rand()
修改为某个值将不会平均分配所有整数.通常这不是问题(您将获得非常非常小的数量),但是如果是这样,则可能需要考虑使用一个比rand()
更强大的随机数生成器.
Of course, as purists will point out, this isn't necessarily going to give you truly uniform values because modding rand()
by some value will not distribute all the integers evenly. This usually isn't a problem (you'll be off by a very, very small amount), but if it is you may want to consider looking into a more robust random number generator than rand()
.
这篇关于C ++随机数生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!