You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现答题错误时让代码循环重试?

如何实现答题错误时让代码循环重试?

你好呀!看来你现在遇到的问题是——答错题目后程序直接退出了,没法重新尝试对吧?其实核心问题出在你原来代码里的return 0;,它会直接终止整个程序,咱们只要把每道题的答题逻辑放到循环结构里,就能实现答错重试的效果啦。

我给你修改后的完整代码,你可以直接参考:

#include <stdio.h>

int main() {
    int myAns; 

    // 第一题:循环直到答对为止
    do {
        printf("If 10 is less than 13, the correct statment for is 10<13? write '1' for True and '0' for False: \n"); 
        scanf("%d", &myAns); 
        if (myAns == 1) { 
            printf("Correct.\n\nNext question\n");
        } else { 
            printf("Wrong, please try again.\n");
        }
    } while (myAns != 1); // 答案不对就重复循环

    // 第二题
    do {
        printf("If 20 is more than 8, the correct statment for is 20<8? write '1' for True and '0' for False: \n"); 
        scanf("%d", &myAns); 
        if (myAns == 0) { 
            printf("Correct.\n\nNext question\n");
        } else { 
            printf("Wrong, please try again.\n");
        }
    } while (myAns != 0);

    // 第三题
    do {
        printf("If 25 is less than 100, the correct statment for is 25>100? write '1' for True and '0' for False: \n"); 
        scanf("%d", &myAns); 
        if (myAns == 0) { 
            printf("Correct.\n\nYou have completed the quiz!\n"); 
        } else { 
            printf("Wrong, please try again.\n");
        }
    } while (myAns != 0);

    return 0; 
}

关键修改点说明:

  • 把每道题的输入、判断逻辑都放进了do-while循环里:这种循环的特点是至少会执行一次题目内容,不管用户第一次答得对不对,很适合答题场景。
  • 去掉了原来错误分支里的return 0;:不再直接退出程序,而是通过循环条件myAns != 正确答案来控制,只要答错就重新回到题目开头让用户输入。
  • 答对后会输出提示并跳出当前循环,自动进入下一题。

如果是初学者的话,先把这个循环逻辑搞明白就好~要是之后想优化,可以考虑加个输入校验(比如防止用户输入非数字导致的异常),不过当前需求这样改就完全够用啦。

备注:内容来源于stack exchange,提问作者Hutchinson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:28:06