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);
switch (input)
{
case 1:
printf("猜数字游戏\n");
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误,重新选择!\n");
break;
}
} while (input);
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-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>
#include <time.h>
void menu()
{
printf("***************************\n");
printf("******* 1. play ******\n");
printf("******* 0. exit ******\n");
printf("***************************\n");
}
void game()
{
int guess = 0;
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;
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;
}
测试

|