简体   繁体   English

当min和max为正数时,Rand()返回负数

[英]Rand() returns negative numbers when min and max are positive

I am using rand() to create random numbers. 我正在使用rand()创建随机数。 When I run my code: 当我运行代码时:

int lowest=10000, highest=90000000000;
int range=(highest-lowest)+1;
for (int index=1; index<2; index++){
c = lowest+int(range*rand()/(RAND_MAX + 1.0));

C returns as both positive and negative numbers. C返回为正数和负数。 Why is this, and how can I fix it? 为什么会这样,我该如何解决?

It's because range * rand() overflowed and wrapped around. 这是因为range * rand()溢出并环绕。

This approach can't be "fixed", because you would just get RAND_MAX of the range possible values, leaving big holes that would never be chosen. 这种方法无法“解决”,因为您只会获得RAND_MAX range可能的值,从而留下了永远无法选择的大漏洞。 (Or, if (INT_MAX - INT_MIN + 1) / (RAND_MAX + 1) is smaller than RAND_MAX , that's how many distinct results you can get) (或者,如果(INT_MAX - INT_MIN + 1) / (RAND_MAX + 1)小于RAND_MAX ,则可以得到多少个不同的结果)

Use the new C++11 random number generators. 使用新的C ++ 11随机数生成器。

If you can't use C++11, then use bitshifting and OR operators to combine multiple rand() results into a single number. 如果您不能使用C ++ 11,请使用移位和OR运算符将多个rand()结果合并为一个数字。 If you got a number outside your range, just try again. 如果您的电话号码超出了您的范围,请重试。 Any method of mapping one range onto another will break most of the nice properties of the pseudo-random number, like uniform distribution. 将一个范围映射到另一个范围的任何方法都会破坏伪随机数的大多数优良属性,例如均匀分布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM