收藏代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 游戏核心逻辑
void game() {
// 生成1~100的随机数
int target = rand() % 100 + 1;
int guess = 0;
// 循环猜数字,直到猜对
while (1) {
printf("请输入你猜的数字:");
scanf("%d", &guess);
if (guess < target) {
printf("猜小了!再试试\n");
} else if (guess > target) {
printf("猜大了!再试试\n");
} else {
printf("恭喜你,猜对了!答案就是%d\n", target);
break; // 猜对后退出循环
}
}
}
// 打印游戏菜单
void menu() {
printf("*********************\n");
printf("***** 1. 开始游戏 *****\n");
printf("***** 0. 退出游戏 *****\n");
printf("*********************\n");
}
int main() {
int choice = 0;
// 设置随机数种子(整个程序只需一次)
srand((unsigned int)time(NULL));
do {
menu(); // 显示菜单
printf("请选择:");
scanf("%d", &choice);
switch (choice) {
case 1:
game(); // 开始游戏
break;
case 0:
printf("游戏结束,再见!\n");
break;
default:
printf("输入错误,请重新选择!\n");
break;
}
} while (choice != 0); // 当选择0时退出循环
return 0;
}
评论