这两个函数是C库中产生随机数的程序。你需要先使用srand()函数赋随机数种子值。然后再使用rand()函数来产生随机数。但是产生随机数的算法较简单,srandom()和random()函数是对这两个函数
的改良,用法也很类似。
但是要注意的是,相同的seed产生的随机数排列是相同的,比如使用了srand(20);假设调用rand()后产生随机数4,6,7,8,然后退出程序,下一次运行时产生的还是4,6,7,8要想每次运行产生不同的随机数就用srand(TIME(NULL));即使用系统当前时间做随机种子。
具体例子:
#include
#include
void main(void)
{
srand(1); //随机种子取为1
int i;
printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand() % 100);
}
编译结果为是十个随机数,并且每次编译运行结果都一样。
下面使用系统时间做随机种子:
#include
#include
#include
void main(void)
{
srand(time(NULL));
int i;
printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand() % 100);
}
由于系统时间随时都在变化,所以每次产生的随机数都不相同