//猜数字游戏
//1. 电脑随机生成一个数字(1~100)
//2. 玩家猜数字
// 玩家猜小了,就告知猜小了
// 玩家猜大了,就告知猜大了
// 直到猜对为止
//3. 游戏可以一直玩
#include <stdio.h>
#include <time.h> //time()函数的头文件
#include <stdlib.h> //rand()和srand()函数的头文件
//游戏界面
void menu()
{
printf("***************************\n");
printf("******** 1. play *********\n");
printf("******** 0. exit *********\n");
printf("***************************\n");
}
//游戏主要功能函数
void game()
{
int guess;
//使用rand生存随机数,rand % 100 + 1 ret的范围就在1~100;
int ret = rand() % 100 + 1;
while (1)
{
printf("猜数字:>");
scanf("%d", &guess);
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
}
//主函数
int main()
{
int input = 0;
//要是用rand就得有srand
//当srand里面的参数在不断变化时,rand就会生成随机数;
//利用time返回时间戳,时间戳是一直在变化的,因此srand内的参数就一直在变化;
//因为srand要求的返回类型是unsigned int,而time返回的类型是time_t*,故将time的类型强转为unsigned int;
//time内部不需要参数,就写一个NULL;
//随机数生成一次就好,不要写进循环;
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;
}
易懂详解 猜数字小游戏
最新推荐文章于 2023-03-31 11:31:15 发布