#include <stdio.h> #include <stdlib.h> #include <time.h> 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
还有以下规则:
Two different initializations with the same seed,instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases.
解决方法
此行为在原始C标准中定义.我没有它的完整副本,但是Open Group的POSIX标准是下一个最好的东西,因为它们包含完整的C标准(带有一些扩展):
http://www.opengroup.org/onlinepubs/000095399/functions/rand.html
The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value,the sequence of pseudo-random numbers shall be repeated. 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.
对任何给定种子的rand()调用的实际结果是实现定义的,除了对于任何种子x,在生成器的种子化之后调用n到rand()必须返回相同的结果.因此,在执行实现时,在调用srand(1)之后,在第一次rand()调用时总是得到41,并且对于第二次rand()调用,您将始终获得相同的结果(无论它是什么),其他实现可能使用产生不同结果的不同算法.
原文地址:https://www.jb51.cc/c/116378.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。