c# - 在 C# 中比较两个数组后如何修复输出?
问题描述
所以我有这个家庭作业,要求我在比较两个数组后将输出分配给标签。我的问题是,比较两个数组后,我分配的输出是错误的。如果在两个数组的特定索引处相等,我应该输出“Y”,如果它们不相等,则输出“N”,但每次我运行代码时,无论如何它都会向所有标签输出“Y” . 如何修复比较后输出的内容?
private void evaluateStudentAnswers()
{
/* Use a "for" loop to cycle through the answerKey[] and studentAnswers[] arrays, and compare the answers
* in the two arrays at each index. If they match, then increment the global variable "correctAnswers"
* and assign the value 'Y' to the corresponding index in the correctOrIncorrect[] array. if they
* don't match, then increment the global variable "incorrectAnswers" and assign the value 'N' to the
* corresponding indes in the correctOrIncorrec[] array. These two variables will be used to calculate
* the grade percentage.
*/
for (int i = 0; i < studentAnswers.Length; i++)
{
for(int j = 0; j < answerKey.Length; j++)
{
// I think the indexes below are being checked if they're the same and I need to make sure not just the
//indexes are the same but the values as well
if (studentAnswers[i] == answerKey[j])
{
correctAnswers++;
for(int k = 0; k < correctOrIncorrect.Length; k++)
{
correctOrIncorrect[k] = 'Y';
}
}
else
{
incorrectAnswers++;
for (int k = 0; k < correctOrIncorrect.Length; k++)
{
correctOrIncorrect[k] = 'N';
}
}
}
}
}
解决方案
我认为您的代码可以简化很多。studentAnswers
假设和之间存在 1-1 映射answerKey
。
for (int i = 0; i < studentAnswers.Length; i++)
{
var studentAnswer = studentAnswers[i];
var answer = answerKey[i];
if (studentAnswer == answer)
{
++correctAnswers;
correctOrIncorrect[i] = 'Y';
}
else
{
++incorrectAnswers;
correctOrIncorrect[i] = 'N'
}
}
所有数组的大小都相同。因此,当我们遍历学生提供的每个答案时,我们知道我们可以在 中找到相应的正确答案answerKey
。此外,正确答案的跟踪也遵循相同的模式,对于每个studentAnswer
,我们都希望在 中记录正确性correctOrIncorrect
,这对应于学生提供的特定答案。因此,我们只需要执行一个循环,因为在i
我们正在处理的所有数组中引用了适当的索引。
推荐阅读
- django - Django:如何删除不再引用的任何外键对象
- python-3.x - 在 Ubuntu 18.04 LTS 服务器上设置使用 headed Selenium 的 Flask 应用程序
- json - 将 json 对象数据导入 Angular 中的 html 前端
- javascript - 如何在我的反应组件中重构这个 ASYNC 调用以使其更具可读性?
- c# - 无法从 Json 解析到 Unity 中的对象数组(Firebase)
- haskell - (x:) 在haskell中是什么意思
- python - 为什么我收到此 python 代码的“运行时错误 (NZEC)”?(SPOJ 抗印迹系统)
- notepad++ - 如何从 Notepad++ 中删除带有特定字符串的 URL?
- css - 令人困惑的 CSS - 任何人都可以解释
- python - 带有希腊字母和 UTF-8 的 Python SQL 语句