首页 > 解决方案 > 在 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';
                        }
                    }
                }
            }
        }

标签: c#asp.netarraysfor-loopoutput

解决方案


我认为您的代码可以简化很多。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我们正在处理的所有数组中引用了适当的索引。


推荐阅读