rand()函数并不能达到真正意义上的产生随机数
rand()函数并不能达到真正意义上的产生随机数.我的意思是rand()产生的数是有规律可循的:由同一个种子产生的随机数是固定不变的.
在C语言里,设置种子的函数是void srand (unsigned seed); .请看下面的几个例程:
/*编译环境vc6.0*/
#include<STDIO.H>
#include<STDLIB.H>
int main()
{
/*设置种子*/
srand(1000);
printf("设置种子为1000后,第一次调用rand()的返回值: %d .\n",rand());
printf("设置种子为1000后,第二次调用rand()的返回值: %d .\n",rand());
srand(1000);
if(rand()==3304)
printf("设置种子后,第n次调用rand()返回的值是确定的.\n");
else
printf("设置种子后,第n次调用rand()返回的值是不确定的.\n");
if(rand()==8221)
printf("设置种子后,第n次调用rand()返回的值是确定的.\n");
else
printf("设置种子后,第n次调用rand()返回的值是不确定的.\n");
return 0;
}
结果:
设置种子为1000后,第一次调用rand()的返回值: 3304 .
设置种子为1000后,第二次调用rand()的返回值: 8221 .
设置种子后,第n次调用rand()返回的值是确定的.
设置种子后,第n次调用rand()返回的值是确定的.
/*编译环境TC2.0*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
clrscr();
/*set the seed*/
srand(1000);
printf("The return value of calling rand() for the first time : %d ,\n",rand());
printf("after setting the seed that is 1000 .\n");
printf("The return value of calling rand() for the second time : %d .\n",rand());
printf("after setting the seed that is 1000 .\n\n");
srand(1000);
if(rand()==18625)
{
printf("The return value of calling rand() is confirmed, \n");
printf("after setting the seed.\n");
}
else
{
printf("The return value of calling rand() is not confirmed, \n");
printf("after setting the seed.\n");
}
if(rand()==14062)
{
printf("The return value of calling rand() is confirmed, \n");
printf("after setting the seed.\n");
}
else
{
printf("The return value of calling rand() is not confirmed, \n");
printf("after setting the seed.\n");
}
getch();
return 0;
}
结果:
The return value of calling rand() for the first time : 18625 ,
after setting the seed that is 1000 .
The return value of calling rand() for the second time : 14062 .
after setting the seed that is 1000 .
The return value of calling rand() is confirmed,
after setting the seed.
The return value of calling rand() is confirmed,
after setting the seed.
从以上二个例程中,可以发现在设置种子之后,每次rand()调用是确定的.
基于以上的原因,C语言提供一个用当前时间来设置随机数生成器的种子randomize().作者建议:在重要的程序设计中,不要使用编译器自动生成的种子.