我无法让 rand()
在 C++ 中工作。 rand()
通常会给我一个非常大的数字。当我尝试使用取模运算符 (%
) 为其指定范围时,无论如何它始终返回 0。
在程序开头植入随机数生成器也无济于事。
最佳答案
我认为如果随机生成器算法将特定的位模式保留为零,这很常见。 (例如,如果低位为零,则某个低位常数的模数将始终为零。)
也许你应该尝试这样的事情:
const int desired_maximum = /* ... */;
int r = (((double)rand()) / RAND_MAX) * desired_maximum;
例如 this manpage link ,它说:
In Numerical Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the following comments are made:
"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in
从来没有任何类似的东西j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));(它使用低阶位)。”j = 1 + (rand() % 10);
关于c++ - 为什么 (rand() % anything) 在 C++ 中总是 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2129705/