I'm having a small problem finding the average from an array that has been read from a text file. The text file has 20 names (first and last) along with a number attached to each name. These numbers have been inputted into a struct the same way the names have--record[i].firstName and record[i].lastName and record[i].testScore. I need to average the test scores but the code isn't doing what I want no matter what I try to compute. This is what I have at the moment, but I've tried many other things. I feel like I'm missing something very simple.
1 2 3 4 5 6 7 8
case 5: // Print the average of all test scores
int ave;
for (int i = 0; i < SIZE; i++)
{
ave = record[i].testScore / SIZE;
}
cout << "The average of all test scores is " << ave << endl;
break;
This is what I tried using before and I'm getting too large of a number. Am I adding wrong?
1 2 3 4 5 6 7 8
case 5: // Print the average of all test scores
int ave;
for (int i = 0; i < SIZE; i++)
{
ave = (record[i].testScore + record[i + 1].testScore) / SIZE;
}
cout << "The average of all test scores is " << ave << endl;
break;
- You haven't initialised any variable that might reasonably construed as a sum to 0.
- All you are doing within the for loop is adding two consecutive array elements together (and going beyond the end of an array - but that's the least of your problems).
- You are still trying to divide by the number of items every time you (incorrectly) add one; WAIT 'til the for loop is finished!
However, computers do not behave exactly like math. Calculations involving floating point numbers are not trivially intuitive. In integer division the left side evolves to 0+1+0+2, i.e. to 3 and the right side to 4, while math says 4½.
Furthermore, the left side has 3 additions and 4 divisions, but the right side has 3 additions and only 1 division. Even if you would get same result, one approach would require more computations than the other. (Insignificant difference in a toy program, but not something one should learn to ignore.)