C语言实现猜数字游戏
猜数字的游戏
-
生成一个随机数
-
猜数字(反馈:大、小、对了)
-
可以反复玩
整体框架
- 菜单
- 实现游戏逻辑的函数
- 主函数
#include <stdio.h>
void menu()
{
printf("***************************\n");
printf("******* 1. play ******\n");
printf("******* 0. exit ******\n");
printf("***************************\n");
}
int main()
{
int input = 0;
do
{
//打印菜单
menu();
printf("请选择:>");
scanf("%d", &input);//1或0或其它
switch (input)
{
case 1:
printf("猜数字游戏\n");
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误,重新选择!\n");
break;
}
} while (input);
//0 表示假,非0表示真
return 0;
}
while (input);
用来判断循环是否继续
- input=1,打印“猜数字游戏”,循环继续
- input=0,打印“退出游戏”,循环终止
- input非1非0,打印“选择错误,重新选择!”,循环继续
编写game()
函数
- 生成随机数(1~100)
- 错误示例
void game()
{
int ret = rand();
printf("%d", ret);
}
错误点:两次测试生成的随机数相同
- 修正
rand()
还需要和srand()
搭配使用
srand()
作用是:设置随机数的生成起点
srand()
参数是一个随机值,由time()
生成时间戳作为它的参数
srand()函数只需要在main()
里调用一次
//设置随机数的生成起点
srand((unsigned int)time(NULL));//拿时间戳作为参数,只调用1次
//C语言获得时间戳:time();同时不使用参数,NULL
//time_t-返回类型-拷贝在vs编译器内查看-long long类型
- 随机数范围设置
若随机数范围(1-100)
rand()%100
的结果即余数0~99
rand()%100+1
的结果即余数1~100
int ret = rand()%100+1;
- 猜数字
while循环可以猜很多次
若猜对了,则break
while (1)
{
printf("请猜数字:>");
scanf("%d", &guess);//输入猜的数字
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你猜对了\n");
break;
}
}
game()
主体
void game()
{
int guess = 0;
while (1)
{
printf("请猜数字:>");
scanf("%d", &guess);//输入猜的数字
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你猜对了\n");
break;
}
}
}
完整代码
#include <stdio.h>
#include <stdlib.h>//rand(); srand();头文件
#include <time.h> //time();头文件
void menu()
{
printf("***************************\n");
printf("******* 1. play ******\n");
printf("******* 0. exit ******\n");
printf("***************************\n");
}
void game()
{
int guess = 0;
//猜数字游戏的逻辑
//1. 生成随机数(1~100)
int ret = rand()%100+1;
//printf("%d\n", ret);
//2. 猜数字
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;
//设置随机数的生成起点
srand((unsigned int)time(NULL));//拿时间戳作为参数,只调用1次
//C语言获得时间戳:time();同时不使用参数,NULL
//time_t-返回类型-拷贝在vs编译器内查看-long long类型
do
{
//打印菜单
menu();
printf("请选择:>");
scanf("%d", &input);//1或0或其它
switch (input)
{
case 1:
game();//调用游戏函数
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误,重新选择!\n");
break;
}
} while (input);
return 0;
}
测试