如果我没有指定srand(),rand()使用什么种子?
这是代码:
#include #include #include int main(void) { int r; int i; for (i = 0; i < 100; i++) { r = rand() % 100 + 1; printf("%d\n", r); } return 0; }
我一直在尝试随机数,但有一天,我忘了把srand()
放进去,但是rand()
函数仍然可以随机输入一个数字(相同的序列)。
问题是,如果我没有指明它,它会使用什么种子?
如果没有调用srand,则rand就像调用了srand(1)一样。
http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand
C标准实际上规定了其他答案中记录的行为:
ISO / IEC 9899:2011§7.22.2.2srandfunction
¶2[…]如果在对
srand
进行任何调用之前调用rand
,则应该生成与首次调用srand
且种子值为1时相同的序列。
man
页说明了以下内容 :
srand()函数将其参数设置为rand()返回的新的伪随机整数序列的种子。 通过使用相同的种子值调用srand(),可以重复这些序列。
如果未提供种子值,则rand()函数将自动播种,值为1。
If rand() is called before any calls to srand() are made, the same sequence shall be generated as when srand() is first called with a seed value of 1.
参考:
http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html
srand()函数将其参数设置为rand()返回的新的伪随机整数序列的种子。 通过使用相同的种子值调用srand(),可以重复这些序列。
如果未提供种子值,则rand()函数将自动播种,值为1。