C语言库函数中的rand()的用法??

来源:百度知道 编辑:UC知道 时间:2024/05/22 00:14:28
include <stdlib.h>
#include <stdio.h>
#include<conio.h>

int main(void)
{
int i;

printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand()%100);
getch();
return 0;
}
为什么每次运行的结果都是一样的??关了重启结果还是一样!!
这结果哪像是随机啊?!!
求高手帮忙解释一下这个库函数的用法?如果能解释一下上面结果不随机问题最好.谢谢!

函数rand所产生的随机数实际上是伪随机数,即反复调用函数rand所产生的一系列数似乎是随机的,但每次执行程序所产生的序列则是重复的。要产生真正的随机数序列,必须在每一次运行前为rand函数提供不同的种子,这是由srand函数提供的。
所以加上srand(time(NULL))就可以产生真正的随机数了。

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

int main(void)
{
int i;
srand(time(NULL));

printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand()%100);
getch();
return 0;
}