问题的提出
在猜数问题中,无论程序执行多少次,,所产生的数字,始终是42,并未达到,”随机数“的效果。
代码
#include<stdio.h>
#include<stdlib.h>
int main()
{
int magic;
int guess;
int counter;
magic=rand()%100+1;
counter=0;
do{
printf("please guess a magic num:“);
scanf("%d",&guess);
counter++;
if(guess>magic)
printf("Wrong! Too big!\n");
else if(guess<magic)
printf("Wrong! Too small!\n");
else
printf("Right!\n");
}while(guess!=magic)
printf("counter=%d\n",counter);
return 0;
}
rand()函数缠上的是一个伪随机数(每次运行程序,产生的都是42)
解决方法
设置随机数种子
在rand函数执行前,加入srand
unsigned int seed; //无符号整型数
srand(seed);
改进:不需要用户键入
- 使用系统时间作为随机数种子
- 用time()函数获得系统时间
加入头文件
#include<time.h>
srand(time(NULL));
用函数的返回值获得系统时间的好处是,就是便于把这个函数调用写到一个表达式中