You need to enable JavaScript to run this app. C#控制台测验应用如何在不新增代码下输出每题作答次数
优惠活动
大模型
产品
解决方案
定价
更多

C#控制台测验应用如何在不新增代码下输出每题作答次数

问题根因

你当前用单值变量count存储作答尝试次数,每次切换到下一题时都会覆盖之前的数值,所以最终统一输出时所有题目都会展示最后一道题的尝试次数,和实际不符。

可行修改方案(无需新增代码行,仅调整现有行内容即可)

因为你受平台限制不能新增代码行数,只需修改现有行的内容,不需要额外声明新变量:

  1. 找到你声明count变量的代码行,直接把单值类型修改为数组:把原来的int count = 1;这类代码改成int[] count = new int[questions.Length];,行数完全不变
  2. 把代码中count++的行修改为count[index]++,给当前正在作答的题目累加尝试次数
  3. 把代码中两处count = attempt的行修改为count[index - 1] = attempt,因为你是先index++再赋值,下标减1对应刚完成的题目序号
  4. 把最终输出的for循环里的count修改为count[i],对应每道题的尝试次数

修改后对应代码片段

if (keys[index] == answer) // Answer is correct
{
    Console.WriteLine();
    Console.WriteLine("Congratulations. That's correct!");
    Console.WriteLine();

    totalScore += markPerQuestion;
    index++;

    Console.WriteLine("The total score is: {0}", totalScore);
    Console.WriteLine("Used attempt(s): {0}", attempt);

    attempt = 1;
    count[index-1] = attempt; // 仅修改本行内容,行数不变
    markPerQuestion = 20;

   
}
else // Answer is incorrect
{
    attempt++;
    count[index]++; // 仅修改本行内容,行数不变

    if (attempt <= 3)
    {
        markPerQuestion /= 2; 

    }

    else if (attempt > 3 && attempt < 5) // The fourth attempt gives zero points
    {
        markPerQuestion = 0;
        totalScore += markPerQuestion;
    }

    else if(attempt >= 5)  // Move to the next question
    {
        Console.WriteLine("Sorry, you used all attempts for that question. Moving to the next question");
        index++;
        markPerQuestion = 20;
        attempt = 1;
        count[index-1] = attempt; // 仅修改本行内容,行数不变
        continue;

    }

    Console.WriteLine("Oops, try again");
}
if ((index > keys.Length - 1 && index > questions.Length - 1)) // Questions and answer keys are finished
{
        for (int i = 0; i < questions.Length; i++)
        {
            Console.WriteLine("Question {0} was answered after {1} attempt(s)", (i + 1), count[i]); // 仅修改本行内容,行数不变
        }
    
    break;
}

修改后运行即可正常展示每道题对应的作答尝试次数,全程没有新增任何代码行,符合你的平台限制要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 02:36:04