Repeated Averages Being Displayed

I'm writing a program which calculates the average of several students' test grades. Whenever I run it only the last students' average is displayed.

For example, if this is my input:

Student 1
    Test 1: 90
    Test 2: 90
    Test 3: 100
    Test 4: 100
Student 1
    Test 1: 94
    Test 2: 90
    Test 3: 91
    Test 4: 89
Student 3
    Test 1: 64
    Test 2: 67
    Test 3: 66
    Test 4: 63

then this is my output:

Student 1  90    90    100    100     65
Student 2  94    90    91     89      65
Student 3  64    67    66     63      65

Does anybody know what I did wrong and how to fix it?

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
//to find the average
double getAverage(int grades[][4], double avg){
    for(int i=0; i<3; i++){
        int sum=0;
        for(int x=0; x<4; x++){
            double(sum=sum+grades[i][x]);
        }
        avg=double((sum)/4);
    }
    return(avg);
}

1
2
3
4
5
6
7
8
9
10
11
12
//to display the average
       for(int i=0; i<3; i++){
            for(int x=0; x<1; x++){
                average[i][x]=getAverage(grades, avg);
                cout<<average[i][x];
                if(x<2){
                    cout<<endl;
                }
                else{
                    cout<<" ";
                }
        }
Seems to be some confusion ing your getAverage function. double is used for declarations, definitions and parameters, not as an arguments or expressions. Also, no need for the second loop.

This would probably work better.

1
2
3
4
5
6
7
double getAverage(int grades[][4], double avg){
    double sum = 0.0;
	for(int i=0; i<3; i++)
            sum += double(grades[i][4]);
        avg= sum/4.0;
    return (avg);
}
Last edited on
That sort of fixed the problem. Now this is what I get:

Student 1  90    90    100    100    39
Student 2  94    90    91     89      49
Student 3  64    67    66     63      49
Your original getAverage function calculates the averages for each student correctly, but stores each calculation in the same variable. The result of each calculation overwrites the previous result.

dacheeba's function, by contrast, accesses outside the boundaries of the grades array resulting in undefined behavior (and botches the calculation to boot.)

I would suggest something more along the lines of:

double getAverage(int grades[][4], unsigned studentIndex) where studentIndex is the index of the student who's grades you want to average.

Then, the function might look something like this:

1
2
3
4
5
6
7
8
9
double getAverage(int grades[][4], unsigned index)
{
    int sum = 0;

    for ( unsigned i=0; i<4; ++i )
        sum += grades[index][i] ;

    return sum / 4.0 ;
}
Last edited on
That fixed it. Thanks, cire!
Topic archived. No new replies allowed.