Mar 20, 2016 at 5:57pm UTC
So every time I run this code it properly calculates Student 1's answers as 100%, but when it loops to Student 2 I get 200% after typing in their answers. I don't know if I am using the 2D array correctly or not and I have no idea where it is going wrong in the code.
Student 1
Answer: abcdefabcdefabcdefab
Score: 100%
Student 2
Answer: abcdefabcdefabcdefab
Score: 200%
Student 3
Answer: abcdefabcdefabcdefab
Score: 300%
int main()
{
int num, correct = 0;
float percent, final_score;
string id;
char answer[5][20];
char key[20] = { 'a','b','c','d','e','f','a','b','c','d','e','f','a','b','c','d','e','f','a','b' };
cout << "Answer key: abcdefabcdefabcdefab" << endl;
cout << "Please enter the number of students to be graded: ";
cin >> num;
int i = 0;
while (i <= num)
{
cout << "Student " << i + 1 << endl;
cout << "Answer: ";
for (int i = 0; i < 1; i++)
{
cin >> answer[i];
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 20; j++)
{
if (answer[i][j] == key[j])
{
++correct;
}
}
}
percent = (float)correct / 20;
final_score = 100 * percent;
cout << "Score: " << final_score << "%" << endl;
i++;
}
system("pause");
return 0;
}
Mar 20, 2016 at 6:54pm UTC
Have you tried to reset your variables to zero at the end of the loop?