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

如何在C#中使用for循环执行指定次数的代码?

在C#中使用for循环实现特定次数的答题重试逻辑

要让代码执行特定次数,你可以用for循环精确控制迭代次数,结合你的答题逻辑,下面是修改后的代码(以最多允许3次尝试为例):

int maxAttempts = 3; // 设定最大尝试次数
bool answeredCorrectly = false;

for (int attempt = 0; attempt < maxAttempts; attempt++)
{
    Console.WriteLine("5. What is group 8 in the periodic table?");
    string answer = Console.ReadLine();
    
    if (answer.ToLower() == "noble gases")
    {
        Console.WriteLine("Correct answer!");
        answeredCorrectly = true;
        break; // 答对后直接退出循环
    }
    else
    {
        // 最后一次尝试时,直接告知正确答案
        if (attempt == maxAttempts - 1)
        {
            Console.WriteLine($"Out of attempts! The correct answer is noble gases.");
            break;
        }
        
        Console.WriteLine("The answer is wrong, pass or try again?");
        string userInput = Console.ReadLine();
        
        if (userInput.ToLower() == "pass")
        {
            Console.WriteLine("The correct answer is noble gases.");
            break;
        }
        // 选择try again时,循环自动进入下一次迭代,直到用完次数
    }
}

关键逻辑说明

  • for循环的核心结构是for(初始化计数器; 循环条件; 计数器更新):这里初始化attempt为0,只要attempt小于设定的maxAttempts就继续循环,每次循环后attempt自增1,以此精准控制执行次数。
  • 答对时直接跳出循环,无需继续尝试。
  • 答错时,若还未用完次数,保留用户选择pass或重试的逻辑;若已是最后一次尝试,直接给出正确答案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:57:34