1. 随机数的生成
1.1rand函数
1.1 要想完成猜数字游戏要用rand函数生成一个随机数,但是rand函数会返回一个为随机数,这个随机数的范围在0~32767。
rand 的函数原型如下: int rand(void);
rand函数的使用要包含头文件:stdlib.h
这里的伪随机数是通过某种算法生成的,而真正的随机数是无法预测下一次的值的,rand通过对叫“种子”的基准值运算生成随机数的,而rand 函数的随机数默认的种子是1,所以想要让随机值变化,就要让种子变化。
1.2srand函数
1.2 srand函数是用来初始化随机数的生成器的。
srand的函数原型如下:void srand(unsigned int seed);
程序中在调⽤rand函数之前先调⽤srand函数,通过srand函数的参数seed来设置rand函数⽣成随机数的时候的种⼦,只要种⼦在变化,每次⽣成的随机数序列也就变化起来了。
那也就是说给srand的种⼦是如果是随机的,rand就能⽣成随机数;在⽣成随机数的时候⼜需要⼀个随机数,这就⽭盾了。
1.3time函数
在程序中我们⼀般是使⽤程序运⾏的时间作为种⼦的,因为时间时刻在发⽣变化的。
在C语⾔中有⼀个函数叫time就可以获得这个时间,time函数原型如下:time_t time (time_t* timer);
time函数会返回当前的⽇历时间,其实返回的是1970年1⽉1⽇0时0分0秒到现在程序运⾏时间之间的差值,单位是秒。返回的类型是time_t类型的,time_t类型本质上其实就是32位或者64位的整型类型。
下面有两种返回方式
1.time函数如果是非NULL的指针,那么也会将这个返回的差值放在time指向的内存中带回去。
2.会以返回值的方式带回时间戳。
time 函数包含的头文件是:time.h
1.4设置随机数的范围
rand() % 100;//范围是0~99
rand() % 100 + 1;//范围是1~100
2.猜数字游戏的实现
下面就是猜数字游戏的代码了~
void menu()
{
printf("****************\n");
printf("*** 1.play ***\n");
printf("*** 0.exit ***\n");
printf("****************\n");
}
void game()
{
int ret = rand() % 100 + 1;
int guess = 0;
int count = 5;
while (count)
{
printf("你还有%d次机会\n", count);
printf("请猜数字:>");
scanf("%d", &guess);
if (guess > ret)
{
printf("猜大了\n");
}
else if (guess < ret)
{
printf("猜小了\n");
}
else
{
printf("恭喜你猜对了\n");
break;
}
count--;
}
if (count == 0)
{
printf("你失败了,正确值是%d\n", ret);
}
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:>");
scanf("%d",&input);
switch(input)
{
case 1:
game();
break;
case 0:
printf("游戏结束\n");
break;
default:
printf("选择错误,请重新输入\n");
break;
}
} while (input);
return 0;
}