Error with Expression

I am trying to calculate the average and when I use
1
2
3
double sum = 0;
double sum += x;
double average = sum/count;

I get an error on the double sum += x;
I am trying to get the average of a random set of numbers in a file, so myFile >> x is what x is.
Last edited on
You already declared sum as a double. No need to remind the compiler every time that sum is a double. sum+=x; is enough.
Thanks, however when I run the program, with the set of numbers
348967
345345
345434
3454
454
453
4
45
45
4
3
45
43
45
45
56
67
78
89
89
the "average" comes out as 4.45 which is no where near correct.
Not much I can say without looking at the code.
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
#include <iostream>    
#include <fstream>					
#include <string>
#include <algorithm>
using namespace std;


int main()
{
	string filename;
	cout << "Enter file name: ";
	cin >> filename;
    ifstream myFile(filename);
	if (myFile.fail())				
	{
		cout << "Error: main(): Failed to open the file: ";
		cout << filename << endl;
	}
	else
	{
		double x;
		int i = 0;
		int count = 0;
		do
		{
			myFile >> x;
			if (!myFile.eof())
			{
				cout << x << endl;
				count ++;
				if(count%20==0)
				{
					myFile >> x;
					double sum = 0;
					sum += x;
					double average = sum/20;
					cout << average << endl;
					cout << "hi" << endl;
					system("pause");
				}
			}
		} while (!myFile.eof());
	}
	myFile.close();
	cout << endl;
	system("pause");


It grabs those numbers from a file called data.txt and pauses the console window when it is full, aka when 20 numbers have rolled through. Im in the process of putting the min max and average out and it won't give me the correct average, heh.
You forgot adding x to sum in your loop, you only do that in the if count%20==0 part, so basically you are just taking a single number and dividing it by count. Also, sum should be declared outside of the loop, else it's value will be lost between iterations.
Last edited on
So the sum += x would go below the first myFile >> x;?
I got it! It does go above and the double average = sum/20 goes below. Thanks!
The code is rather poorly structured. I would do it like this:
1
2
3
4
5
6
7
8
9
10
11
12
int count=0;
double sum=0;

do {
	myFile >> x;
	cout << x << endl;
	sum+=x;
	count++;
}while (!myFile.eof());

double average = sum/count;
cout << average << endl;
Another hitch though, when the program runs, I get the average only when the count%20 = 0. How would I have it so that if there were only 6 numbers before the end of file it would still give me the average of those numbers?
Topic archived. No new replies allowed.