c++ - 自定义 rand() 函数返回相同的值

标签 c++ c random

作为引用,我遵循了这个 thread .

我从 main() 函数调用这个函数,它返回 [0, N] 范围内的随机值:

int randr(int min, int max) { int r = (rand() % (max+1-min)+min); return r; }

例如:

int main()
{
unsigned int r=128;
while(r--)
{
    int a = randr(0, 63);
    int b = randr(64, 127);
    printf("%d   %d\n", a, b);
}
return 0;
}

问题是,每次执行程序时,变量 ab 总是包含相同的生成值,为什么 (我的意思是 printf 总是终端上的相同数据)

最佳答案

来自 rand 的手册页:

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

最后一句话尤为重要。使用相同的种子,您将始终获得相同的伪随机数序列。由于您没有明确使用 srand(),因此您的种子始终为 1。

关于c++ - 自定义 rand() 函数返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15424406/

相关文章:

C++ - 如何读取系统文件

c - 如何在 C 中使用大于和小于(> 和 <)比较 float

c - 为什么程序要双输出?

java - 如何生成 16 个字符限制为 "a"和 "b"的所有可能的字符串?

c++ - 什么加密随机生成器 C 代码可以在 WP8.1 上使用?

c++ - 从另一个桌面捕获屏幕截图

c++ - GCC 下的对象加载段错误

c++ - g++ 在构建点云库时未定义对符号 '__cxa_free_exception@@CXXABI_1.3' 的引用

c - 用于嵌入式设备的 C 语言微型垃圾收集器

c++ - 无法使用种子生成高斯分布