所以我有这个功课分配,要求我在比较两个数组后将输出分配给标签。我的问题是,在比较两个数组后,我分配的输出是错误的。如果在两个数组的特定索引相等时我应该输出'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
和answerKey
之间有1-1的映射。
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
在我们正在处理时引用所有数组中的适当索引。
如果studentAnswers.Length == answerKey.Length == correctOrIncorrect.Length
然后
for (int i = 0; i < studentAnswers.Length; i++)
{
if(studentAnswers[i] == answerKey[j])
{
correctAnswers++;
correctOrIncorrect[k] = 'Y';
}
else
{
incorrectAnswers++;
correctOrIncorrect[k] = 'N';
}
}
由于这是一项任务我不会给出答案:)但是因为你被困,我鼓励你使用下面的指导。
您的代码中不需要这两个
由于数组必须具有相同的大小/顺序,因此您只需要遍历它们一次。另外,我发现三元分配比块更明确:
Func<bool, int> toInt = (b) => b ? 1 : 0;
for (int i = 0; i < studentAnswers.Length; i++)
{
var studentAnswer = studentAnswers[i];
var answer = answerKey[i];
var isCorrect = studentAnswer == answer;
correctOrIncorrect[i] = isCorrect ? 'Y' : 'N';
correctAnswers = isCorrect ? 1 : 0; // toInt(isCorrect)
incorrectAnswers = !isCorrect ? 1 : 0; // toInt(!isCorrect)
}
}
或者在LINQ中(仅仅因为它值得学习,但可能不适合做作业):
correctOrIncorrect = answerKey.Zip(studentAnswer, (a,b) => a == b ? "Y" : "N").ToArray();
incorrectAnswers = correctOrIncorrect.Count(x => x == "Y");
...