Chr*_*men 1 c# asp.net arrays for-loop output
所以我有这个作业分配,要求我在比较两个数组后将输出分配给标签。我的问题是比较两个数组后,分配的输出是错误的。如果在两个数组的特定索引处相等,我应该输出“ 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';
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为您的代码可以简化很多。假设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'
}
}
Run Code Online (Sandbox Code Playgroud)
所有阵列的大小均相同。因此,当我们遍历学生提供的每个答案时,我们知道可以在中找到相应的正确答案answerKey。同样,对正确答案的跟踪也遵循相同的模式,对于每个studentAnswer,我们要在中记录正确性correctOrIncorrect,该正确性对应于学生提供的特定答案。这样,我们只需要执行一个循环,因为在处理过程中,i引用了所有数组中的适当索引。