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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  #include <iostream>
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

1) before you can average your grade I recommend getting the grades first.

1
2
3
4
5
6
7
8
//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:

1
2
3

      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.