酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

猜数字游戏是令游戏机随机产生一个100以内的正整数,用户输入一个数对其进行猜测,需要你编写程序自动对其与随机产生的被猜数进行比较,并提示大了(“too big”),还是小了(“too small”),相等表示猜到了。如果猜到,则结束程序。程序还要求统计猜的次数,如果1次猜出该数,提示“bingo!”;如果3次以内猜到该数,则提示“lucky you!”;如果超过3次但是在n(>3)次以内(包括第n次)猜到该数,则提示“good guess!”;如果超过n次都没有猜到,则提示“game over”,并结束程序。如果在到达n次之前,用户输入了一个负数,也输出“game over”,并结束程序。 输入格式: 输入第一行中给出两个不超过100的正整数,分别是游戏机产生的随机数、以及猜测的最大次数n。最后每行给出一个用户的输入,直到出现负数为止。 输出格式: 在一行中输出每次猜测相应的结果,直到输出猜对的结果或“game over”则结束。 用c语言

下面是一个用C语言实现的猜数字游戏程序,满足题目中的所有要求: ```c #include <stdio.h> int main() { int secretNumber, maxAttempts, userGuess, attempts = 0; // 读取随机数和最大尝试次数 scanf("%d %d", &secretNumber, &maxAttempts); while (1) { scanf("%d", &userGuess); if (userGuess < 0) { printf("game over\n"); break; } attempts++; if (userGuess == secretNumber) { if (attempts == 1) { printf("bingo!\n"); } else if (attempts <= 3) { printf("lucky you!\n"); } else if (attempts <= maxAttempts) { printf("good guess!\n"); } else { printf("game over\n"); } break; } else if (userGuess > secretNumber) { printf("too big\n"); } else { printf("too small\n"); } if (attempts >= maxAttempts) { printf("game over\n"); break; } } return 0; } ``` 代码说明: 1. 输入部分: - 首先读取两个整数:`secretNumber`(游戏机生成的随机数)和`maxAttempts`(最大尝试次数)。 - 然后在一个无限循环中读取用户的猜测`userGuess`。 2. 判断部分: - 如果用户输入的数是负数,输出`game over`并结束程序。 - 每次用户输入一个数,增加尝试次数`attempts`。 - 如果用户猜对了数字: - 如果是第一次猜对,输出`bingo!`。 - 如果在3次以内猜对,输出`lucky you!`。 - 如果在`maxAttempts`次以内猜对,输出`good guess!`。 - 如果超过了`maxAttempts`次猜对,输出`game over`。 - 如果用户猜错了数字,根据猜测的大小输出`too big`或`too small`。 - 如果尝试次数达到了`maxAttempts`,输出`game over`并结束程序。 示例输入输出: 假设输入如下: ``` 50 5 30 70 40 60 50 ``` 输出将是: ``` too small too big too small too big good guess! ``` 假设输入如下: ``` 50 3 30 70 -1 ``` 输出将是: ``` too small too big game over ``` 这个程序能够正确处理各种输入情况,并按照题目要求输出相应的结果。 [2024-10-31 09:15:00 | AI写代码神器 | 613点数解答]

相关提问