我不明白 srand()
的含义在<time.h>
创建一个随机数。
这是我的代码:
/* srand example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
printf ("First number: %d\n", rand()%100);
srand (time(NULL));
printf ("Random number: %d\n", rand()%100);
srand (1);
printf ("Again the first number: %d\n", rand()%100);
return 0;
}
结果是:
First number: 41
Random number: 13
Again the first number: 41
为什么结果是srand(1)
不同于srand(2)
?
为什么srand(1)
的结果是或srand(2)
不断出现?
为什么我必须使用 srand(time(NULL))
为了创建动态随机数?
最佳答案
如果你看docs :
Seeds the pseudo-random number generator used by
std::rand()
with the value seed.
rand()
有一些内部状态,它从一次调用到下一次调用都保留着这些状态。该函数是确定性的 - 但我们可以将其输出视为伪随机的。因此产生的值(value):
srand(1);
rand();
对于给定的实现,将始终相同。这就是为什么注释指出:
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
关于c++ - srand()的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305016/