Why Won't This Show Correct Average?

Everything runs fine so far. It reads from an option of 2 different files provided by my professor in his compiler containing various numbers. I just don't know how to average them all correctly. I think the "average = (sum / counter);" might be in the wrong spot. Thank you.

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
55
56
57
58
59
60
61
62
#include <iostream>
#include <fstream>
#include <iomanip>
#include <climits>

using namespace std;

int main()
{
    int counter = 0;
    double numberArray[100], sum = 0, average = 0;
    ifstream file;
    string fileChoice, data1 = "data1.txt", data2 = "data2.txt";

    cout << setprecision(2) << fixed;
    cout << "Please enter the file name to open: ";
    cin >> fileChoice;
    cout << "Reading file: " << fileChoice << endl;

    if (fileChoice == data1 || fileChoice == data2)
    {
        file.open(fileChoice.c_str());

        file >> numberArray[counter];

        while (file)
        {
            counter++;

            file >> numberArray[counter];
        }
        sum += numberArray[counter];

        average = (sum / counter);

        cout << "There were " << counter << " numbers in the file." << endl;
        cout << "The average of the numbers was " << average << endl;
        cout << "Here is your report" << endl;

        for (int i = 0; i < counter; i++)
        {
            if (numberArray[counter] < average)
            {
                cout << numberArray[i] << " is below average" << endl;
            }
            else if (numberArray[counter] > average)
            {
                cout << numberArray[i] << " is above average" << endl;
            }
            else if (numberArray[counter] == average)
            {
                cout << numberArray[i] << " is exactly average" << endl;
            }
        }
    }
    else
    {
        cout << "Cannot locate the desired file!" << endl;

        return 0;
    }
}
Lines 31 and 32.

Also, look at what you are doing on lines 42, 46, and 50.

Hope this helps.
@Duthomhas What about those lines...
Further hints to expand:

1. lines 31 and 32 determine the extent of the loop - keep in mind the sum is a running sum that is continually updated with the next number read in from the file, but there is meant to be only one average.

2. lines 42, 46 and 50 - are you absolutely sure its right to compare the same value from the array to the average?

3. If none of that means much, stay with your program for now and just add a line or two to cout counter, numberArray, sum and average for each pass through the loop you already have.
Topic archived. No new replies allowed.