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.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
usingnamespace 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.
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?