C#控制台测验应用如何在不新增代码下输出每题作答次数
问题根因
你当前用单值变量count存储作答尝试次数,每次切换到下一题时都会覆盖之前的数值,所以最终统一输出时所有题目都会展示最后一道题的尝试次数,和实际不符。
可行修改方案(无需新增代码行,仅调整现有行内容即可)
因为你受平台限制不能新增代码行数,只需修改现有行的内容,不需要额外声明新变量:
- 找到你声明
count变量的代码行,直接把单值类型修改为数组:把原来的int count = 1;这类代码改成int[] count = new int[questions.Length];,行数完全不变 - 把代码中
count++的行修改为count[index]++,给当前正在作答的题目累加尝试次数 - 把代码中两处
count = attempt的行修改为count[index - 1] = attempt,因为你是先index++再赋值,下标减1对应刚完成的题目序号 - 把最终输出的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
相关产品推荐
相关产品推荐

