在学习翁恺老师的c课程中,有这样一个猜数游戏
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
int main()
{
srand(time(0));
int number=rand()%100+1;
int count=0;
int a=0;
printf(“我已经想到了一个1到100的数。”);
do{
printf(“猜猜这个1到100的数:\n”);
scanf("%d",&a);
count++;
if(a>number){
printf(“你的数猜大了\n”);
}
else if(a<number){
printf(“你的数猜小了\n”);
}
}
while(a!=number);
printf(“你用了%d次就得出了答案\n”,count);
}
其中srand(time(0));是不是很陌生?
学过其他语言的应该已经猜到了,他是作为rand()的种子出现的,因为电脑取随机数是伪随机,只要种子一样,则取出的数一定一样。
这里用time(0)这个函数,则是返了当前的时间值。这个值是按照时间而变化的,所以,srand(unsigned(time(NULL)))这个函数的作用,就是一个简单的设定随机数的种子方法。通过这个函数,可以得到每次都不一样的随机数。
对了,注意把time.h的库包含进去哦。