您的位置:首页 > 其它

随机数赋值,srand()放在循环体和循环体外的区别

2012-12-06 16:48 507 查看
这是一段由下面一段代码引发的血案:

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define counter 1
#define bool int
#define true 1
#define false 0
int main()
{
bool flag[100];
bool light=false;
int count=0;
int times=0;
int temp;
for(temp=0;temp<100;temp++)
flag[temp]=false;
//srand(time(NULL));
while(true)
{
srand(time(NULL));
temp=rand()%100;
times++;
if((flag[temp]==false)&&(light==false)&&(temp!=counter))
{
flag[temp]=true;
printf("%d ",temp);
light=true;
}
if((temp==counter)&&(light==true))
{
light=false;
count++;
}
//printf("times:%d\n",times);     srand丢循环体内,可执行。
if(count==99)
break;
}
printf("times:%ddays later:\n",times);
}


这段代码的作者抱怨srand()函数放到循环体内部一直无输出,但实际上会有输出的,只不过需要点时间。下面的是要讨论的重点,首先先看几个代码:

代码1:

/*结果永远是1740948824*/
#include<stdio.h>
#include<stdlib.h>

int main()
{
int i=0;
for(i=0;i<10;i++)
printf("%d",rand()%10);
printf("\n");
return 0;
}


代码2:

/*加了srand以后,结果永远是1924762269,但是,和原来的1740948824不一样了*/

#include<stdio.h>
#include<stdlib.h>

int main()
{
int i=0;
srand(10); //加了个srand
for(i=0;i<10;i++)
printf("%d",rand()%10);
printf("\n");
return 0;
}


代码3:

/*把srand放在循环里,输出永远是1111111111*/
#include<stdio.h>
#include<stdlib.h>

int main()
{
int i=0;
//srand(10);  //这条去掉
for(i=0;i<10;i++)
{
srand(10);  //放在循环里
printf("%d",rand()%10);
}
printf("\n");
return 0;
}


rand函数是一个伪随机数列。在没有srand的情况下,每次生成的序列都是一样的。

而运行了srand(n);以后在n相同的情况下,rand每次生成的序列还是一样的。

就是说,如果每次运行一次srand(n);再运行rand,生成的第一个数都是一样的。(time(NULL),是以秒为单位,一秒钟数字增加一个)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: