C语言while循环lives计数器为负未退出问题求助
答题游戏lives计数器问题解答
你的问题核心是while循环逻辑错误,导致lives降到0后没及时终止答题,还会继续减成负数,具体问题和修复方法如下:
问题原因
- 你把两道题的代码都塞进了一次循环执行里——哪怕第一题答错后lives变成0,代码还是会继续执行第二题,自然会让lives再减1变成负数。
- 循环里答题结束后直接设置
ingame=0,导致循环只会执行一次,完全没起到“lives不够就终止游戏”的控制作用。 while条件里的lives<=3是多余的,lives初始是3只会递减,这个条件不会限制任何逻辑。
修复方案
- 每答完一题就检查lives是否为0,是的话立即终止循环,不再执行后续题目。
- 移除
ingame=0的提前赋值,让循环根据lives>0的条件自动控制流程。 - 去掉多余的
lives<=3条件,简化循环判断。
修改后的代码
#include<stdio.h> int main (void) { //quiz variables int gamestart, ingame = 1; int scr1, scr2, scr3, scr4, scr5; int ans1, ans2, ans3, ans4, ans5; char name[25]; int total = 0; //start of quiz printf("--------Hello welcome to the quiz game!--------\n"); printf("----Press 1 to start the game and 0 to quit----\n"); scanf("%d", &gamestart); //quiz code int lives = 3; // 简化循环条件,只保留必要控制 while (ingame == 1 && lives > 0) { if (gamestart == 1) { // 仅首次进入游戏时输入名字 static int first_run = 1; if (first_run) { printf("Enter your first name: "); scanf("%s", name); printf("Hello %s! Let's start the game...\n", name); first_run = 0; } printf("First Question: What does “www” stand for in a website browser?\n"); printf("1. Whole Wide World 2. Whole Wide Web\n"); printf("3. World Wide Web 4. World Wide Whole\n"); printf("Enter the number of your answer: "); scanf("%d", &ans1); switch(ans1){ case 1: printf("Wrong Answer. You gain 0 points"); scr1 = 0; break; case 2: printf("Wrong Answer. You gain 0 points"); scr1 = 0; break; case 3: printf("Correct Answer! You gain 5 points!"); scr1 = 5; break; default: printf("Wrong Answer. You gain 0 points"); scr1 = 0; break; } total += scr1; if (scr1 == 0 ) lives--; printf("\nLives left: %d", lives); printf("\nYour total score this round is %d ", total); printf("\n"); // 检查lives是否耗尽,是则直接结束游戏 if (lives <= 0) { printf("Game over! You have no lives left.\n"); ingame = 0; break; } printf("\nNext Question...\n"); printf("What is \"cynophobia\"?\n"); printf("1. Fear of dogs 2. Fear of cats\n"); printf("3. Fear of cyanide 4. Fear of the color blue\n"); printf("Enter the number of your answer: "); scanf("%d", &ans2); switch(ans2){ case 1: printf("Correct Answer! You gain 5 points!"); scr2 = 5; break; case 2: printf("Wrong Answer. You gain 0 points"); scr2 = 0; break; case 3: printf("Wrong Answer. You gain 0 points"); scr2 = 0; break; default: printf("Wrong Answer. You gain 0 points"); scr2 = 0; break; } total += scr2; if (scr2 == 0) lives--; printf("\nLives left: %d", lives); printf("\nYour total score this round is %d ", total); // 答题结束后终止循环 ingame = 0; } else if (gamestart == 0) { ingame = 0; } else { printf("Invalid Keyword\n"); printf("----Press 1 to start and 0 to quit----\n"); scanf("%d", &gamestart); } } printf("\n\n\nThank you!"); return 0; }
额外说明
- 新增
static int first_run避免重复让用户输入名字,符合正常游戏流程。 - 每道题后都检查lives状态,确保lives耗尽时立即终止游戏,不会继续执行后续题目。
内容的提问来源于stack exchange,提问作者Ronin
相关产品推荐
相关产品推荐

