Calculating an Average

I have an assignment where I have 20 students with different test scores. The test score is set as a structure. I'm having trouble setting up the function to find the average. I'll put what I have.

1
2
3
4
5
6
7
  case 5:
			for (int i = 0; i < 20; i++)
			{
				float average = 0;
				average = (s[i].testscore) / 20;
				cout << average << endl;
			}
1
2
3
4
5
6
7
8
9
10
11
const int NUM_STUDENTS = 20 ;

// ...

// sum up all the scores
double sum_scores = 0 ;
for( int i = 0 ; i < NUM_STUDENTS ; ++i ) sum_scores += s[i].testscore ;

// divide by number of students to get the average
const double average = sum_scores / NUM_STUDENTS ;
std::cout << "average: " << average << '\n' ;
This is my code and it gave me a negative:

1
2
3
4
5
6
7
8
9
double sum = 0;

			for (int i = 0; i < 20; i++)
			{
				sum += s[i].testscore;
			}

			const double average = sum / 20;
			cout << "The average is " << average << "\n";
Make sure that your test scores are correct. Print out some diagnostic information:

1
2
3
4
5
6
7
8
9
10
11
double sum = 0;

for (int i = 0; i < 20; i++)
{
    sum += s[i].testscore;
    cout << "i == " << i << "  test score == " << s[i].testscore 
         << "  sum == " << sum << '\n' ;
}

const double average = sum / 20;
cout << "The average is " << average << '\n';
Last edited on
I saw in the diagnostics my test scores were were incorrect. I fixed it and got it now. Thanks!
Topic archived. No new replies allowed.