c++ - 为什么 (rand() % anything) 在 C++ 中总是 0?

标签 c++ random

我无法让 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/

相关文章:

c++ - "using namespace std;"没有任何#include?

c++ - 禁用 glog 的 "LOG(INFO)"日志记录

c++ - 如何成为C++库开发人员?

java - `Random.ints(origin, bound)` 、 `.longs(origin, bound)` 等的 API 是否缺少功能?

javascript - 通过 jQuery 对随机字段项进行排序

c++ - 从常量变量复制 vector

c++ - 从 sqlite3_stmt* 检索 sqlite3*

testing - 在顽固的测试套件中使用包含随机数的 .txt 文件

python - scipy.stats 种子?

c# - Unity 中的随机生成 (C#)