2004-7-27 17:21
gbunix
我写一个小程序是使用rand()返回随机数,但发现rand()返回的是个固定的数,为什么?
2004-7-27 17:34
大漠孤星
呵呵。<br /><br />你的小程序不会是<br /><br />main()<br />{<br /> printf ("%d\n",rand());<br />}<br /><br />然后一次一次执行结果吧?<br /><br />呵呵。。。<br /><br />试试这个<br /><br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1--><br />main()<br />{<br /> int i;<br /> for ( i = 0;i <100;i ++ )<br /> {<br /> printf ("%d\n",rand());<br /> printf ("%ld\n",random());<br /> }<br /> exit(0);<br />}<br /><!--c2--></div><!--ec2-->
2004-7-27 17:36
gbunix
谢了,但为什么?
2004-7-27 18:06
大漠孤星
<!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1--><br />The spectral properties of rand are limited. The drand48(S) function<br /> provides a much better, though more elaborate, random-number generator.<br /><br /> The following functions define the semantics of the functions rand and srand.<br /><br /> static unsigned long int next = 1;<br /> int rand()<br /> {<br /> next = next * 1103515245 + 12345;<br /> return ((unsigned int)(next/65536) % 32768);<br /> }<br /> void srand(seed)<br /> unsigned int seed;<br /> {<br /> next = seed;<br /> }<br /><br /> Specifying the semantics makes it possible to reproduce the behavior of<br /> programs that use pseudo-random sequences. This facilitates the testing of<br /> portable applications in different implementations.<br /><br /><br /><!--c2--></div><!--ec2--><br /><br />这种伪随机数是由随机种子根据一定的计算方法计算出来的数值。<br />算法是死的,随机种子一定,那么产生的随机数就是固定的。<br /><br /><br />我大约知道了。 <!--emo&:awkard:--><img src='style_emoticons/default/awkard.gif' border='0' style='vertical-align:middle' alt='awkard.gif' /><!--endemo--> <br /><br />for循环里的rand调用是在同一个进程中,第一次调用完了的返回值是第二次rand调用<br /><br />的seed值。。。估一直在变化。。<br /><br /><br />如果程序中只调用一次rand,从rand的算法来看,它的seed值是固定的。<br /><br />当然不管怎么调用,调用多少次,不在同一个进程里调用返回的值都是一样的。<br /><br />我想,应该是这样的解释吧。
2004-7-28 07:48
thrips
调用rand之前要用srand设一下起始值。起始值相同的话,随机序列也就相同。一般用系统时间作为起始值,这样每次执行的随机序列就是不同的了。
2007-11-17 14:58
jas199931
大漠孤星:
请问你的这段代码是从何处取得,是最新公布的代码吗?
static unsigned long int next = 1;
int rand()
{
next = next * 1103515245 + 12345;
return ((unsigned int)(next/65536) % 32768);
}
void srand(seed)
unsigned int seed;
{
next = seed;
}
多谢了先。
2007-11-19 13:50
littlestar
用当前时间做种子。
srand(time(NULL))
页:
[1]
Powered by Discuz! Archiver 5.5.0
© 2001-2006 Comsenz Inc.