作为引用,我遵循了这个 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;
}
问题是,每次执行程序时,变量 a
和 b
总是包含相同的生成值,为什么 (我的意思是 printf 总是终端上的相同数据)?
最佳答案
来自 rand
的手册页:
The
rand()
function returns a pseudo-random integer in the range 0 toRAND_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 byrand()
. These sequences are repeatable by callingsrand()
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/