### Need help with this code:

I have written this code to take 10 grades and average them, but the average is always like 75383571085315%. I have no idea why the number is so large and wrong. Can somebody help me?
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354`` `````` #include using namespace std; /********************************************************************** * GETGRADES * ***********************************************************************/ void getGrades(int grades[]) { for (int i = 0; i < 10; i++) { cout << "Grade " << i + 1 << ": "; cin >> grades[i]; } } /******************** *AVERAGEGRADES * ******************/ int averageGrades(int grades[]) { int sumaverage = 0; for (int i = 0; i < 10; i++) { sumaverage += grades[i]; } return sumaverage; } /************* *DISPLAY * ************/ void display(int average) { cout << "Average Grade: " << average << "%\n"; } /******* *MAIN * *******/ int main() { int grades[10]; int average = averageGrades(grades); getGrades(grades); display(average); return 0; } ``````
I do not see you dividing by 10 in your average might be part of your problem. You are simply summing the values.

Edit -- removed erroneous information thanks @Chervil for catching it.
Last edited on
You have things in main() occurring in the wrong sequence. You can't prepare a meal until you fetched the ingredients.
Last edited on
Couple things I noticed

 ``12345678`` ``````//From This int average = averageGrades(grades); getGrades(grades); // To this getGrades(grades); int average = averageGrades(grades); ``````

2) I could be wrong with this one, but I think your unintentionally increase the value of I at:

 ``123`` `````` cout << "Grade " << i + 1 << ": "; ``````

Im not at a computer right now so you might want test that yourself

but switch the getgrades and the calculate average averages function calls and you might see better results

knowclue wrote:
Another problem is that your array is being passed by value. This means that a copy is being changed and nothing is being changed in the actual array.

That's a misunderstanding.

When an array is passed as a function parameter, what is actually passed is a pointer to the start of the array. Yes, the pointer itself is passed by value, but that doesn't prevent it from being dereferenced to access the actual contents of the original array.
@Chervil Thank you for correcting that. I hardly ever use regular arrays anymore and completely overlooked that. I can't believe I just did that.
Last edited on
Oh, thanks for the advice everyone. I didn't realize i was trying to get the average before i got the grades, so it was messing everything up. Thanks again.
Topic archived. No new replies allowed.