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

数学游戏代码异常:用户仅能答错一次即跳转下一题,求排查

代码问题分析与修复方案

问题根源

  • 未重新获取用户输入:代码仅在attempts == 0时生成题目并获取输入,答错后attempts > 0的循环中,不会触发新的输入操作,导致一直使用第一次错误的sum值重复判断,attempts会被快速累加至3,表现为只允许一次错误就跳转下一题。
  • 错误分支逻辑缺失:答错后仅累加attempts,未在attempts < 3时提示用户重新输入,直接continue进入下一次循环,程序根本没给用户第二次、第三次答题的机会。

修复后的代码

nQuestions = 0
cAnswers = 0
lvl = get_level()
while nQuestions != 10:
    attempts = 0
    x, y = generate_integer(lvl)
    answer = x + y
    # 内部循环处理当前题目的3次尝试
    while attempts < 3:
        try:
            user_input = int(input(f"{x} + {y} = "))
            if user_input == answer:
                cAnswers += 1
                break  # 答对,跳出尝试循环
            else:
                attempts += 1
                if attempts < 3:
                    print("EEE")  # 可选:提示输入错误
        except ValueError:
            # 处理用户输入非整数的情况
            attempts += 1
            print("EEE")
    # 三次全答错,显示正确答案
    if attempts == 3:
        print(f"{x} + {y} = {answer}")
    nQuestions += 1

修复说明

  • 为每个题目单独设置内部循环,专门处理3次答题尝试,逻辑更清晰。
  • 每次尝试都重新获取用户输入,彻底避免复用旧的错误值。
  • 增加try-except块处理非整数输入的异常场景(可根据需求调整或移除)。
  • 答对后直接跳出尝试循环,答错且未到3次时提示用户重新输入,完全符合需求逻辑。

内容的提问来源于stack exchange,提问作者Big_Port

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:42:39