I have just run into a problem that is probably easy to fix, but I just can't figure out what the answer is. My problem is in my getData function. After entering in test scores for each student and trying to print out the average, my averages are always wrong after the first student. Can someone please tell me why that is. Thanks for all the help!
// In this program I declare a structure that consists of two character arrays,
// an integer array, and an average variable. I will allow the user to enter information for
// 29 different variables of the structure then calculate the average test score of each
// member.
#include <iostream>
usingnamespace std;
constint NUMCHARS = 20;
constint NUMTESTS = 4;
constint NUMSTUDS = 2;
struct Student {
char firstName[NUMCHARS+1];
char lastName[NUMCHARS+1];
int grades[NUMTESTS];
double average;
};
void getData(Student students[]);
int main()
{
Student students[NUMSTUDS];
getData(students);
}
void getData(Student students[])
{
int i,j;
double sum=0;
for(i=0;i<NUMSTUDS;i++) {
cout << "Please enter the first name of student #" << i+1 << ": ";
cin >> students[i].firstName;
cout << "Please enter the last name of student #" << i+1 << ": ";
cin >> students[i].lastName;
for(j=0; j<NUMTESTS; j++) {
cout << "Please enter test score #" << j+1 << ": ";
cin >> students[i].grades[j];
sum+=students[i].grades[j];
}
cout << endl << endl;
students[i].average = sum / NUMTESTS;
}
for(i=0; i<NUMSTUDS; i++) {
cout << students[i].average << endl;
}
}
You need to reset sum back to 0 after each iteration of the for loop.
1 2 3 4 5
for(i=0;i<NUMSTUDS;i++) {
sum = 0; // reset variable for new student
cout << "Please enter the first name of student #" << i+1 << ": ";
cin >> students[i].firstName;