C语言按照模块化程序设计方法设计猜数游戏,要求如下,显示一个菜单,让用户选择游戏的方式:(1)选择1,则猜一个数(2)选择2,则猜多个数;(3)选择3,退出游戏。其中,猜每一个数的方式有3种:只猜一次,猜到对为止,最多猜10次。
时间: 2024-05-05 16:16:36 浏览: 13
以下是C语言按照模块化程序设计方法设计的猜数游戏代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 生成一个随机数
int generateNumber(int min, int max) {
srand(time(NULL));
return rand() % (max - min + 1) + min;
}
// 猜一个数游戏
void guessOneNumber() {
int min = 1, max = 100;
int number = generateNumber(min, max);
int guess, attempts = 0;
printf("猜一个%d到%d之间的数,最多猜10次\n", min, max);
do {
printf("请输入你猜的数:");
scanf("%d", &guess);
attempts++;
if (guess == number) {
printf("恭喜你,猜对了!你用了%d次机会。\n", attempts);
return;
} else if (guess < number) {
printf("你猜的数太小了,请继续猜。\n");
} else {
printf("你猜的数太大了,请继续猜。\n");
}
} while (attempts < 10);
printf("很遗憾,你已经猜了10次,游戏结束。正确答案是%d。\n", number);
}
// 猜多个数游戏
void guessMultipleNumbers() {
int min = 1, max = 100;
int number, guess, attempts = 0;
char choice;
printf("猜多个%d到%d之间的数,直到退出游戏。\n", min, max);
do {
number = generateNumber(min, max);
attempts = 0;
printf("你要猜%d次这个数,你可以选择:(1)只猜一次,(2)猜到对为止,(3)最多猜10次。\n", attempts);
do {
printf("请输入你的选择:");
scanf(" %c", &choice);
} while (choice != '1' && choice != '2' && choice != '3');
switch (choice) {
case '1':
attempts = 1;
break;
case '2':
attempts = -1;
break;
case '3':
attempts = 10;
break;
}
do {
printf("请输入你猜的数:");
scanf("%d", &guess);
attempts++;
if (guess == number) {
printf("恭喜你,猜对了!你用了%d次机会。\n", attempts);
} else if (guess < number) {
printf("你猜的数太小了,请继续猜。\n");
} else {
printf("你猜的数太大了,请继续猜。\n");
}
} while (guess != number && attempts <= 10);
if (attempts > 10) {
printf("很遗憾,你已经猜了10次,正确答案是%d。\n", number);
}
do {
printf("你还要继续玩吗?(Y/N)");
scanf(" %c", &choice);
} while (choice != 'Y' && choice != 'N');
} while (choice == 'Y');
}
// 主函数
int main() {
char choice;
do {
printf("请选择游戏的方式:(1)猜一个数,(2)猜多个数,(3)退出游戏。\n");
scanf(" %c", &choice);
switch (choice) {
case '1':
guessOneNumber();
break;
case '2':
guessMultipleNumbers();
break;
case '3':
printf("游戏结束,谢谢参与!\n");
break;
default:
printf("输入有误,请重新选择。\n");
break;
}
} while (choice != '3');
return 0;
}
```
使用方法:将代码保存为.c文件,用C语言编译器编译运行即可。