#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
//declare Vars and constants
double input;
double total = 0.0;
ifstream myfile;
myfile.open ("prices.txt");
if (myfile.is_open())
{
//Enter input
while(myfile.eof() == false)
{
myfile>>input;
total = total + input;
}//end while
myfile.close();
}//end if
else
cout << "Error opening file\n";
system("pause");
return 0;
} // end of main funct.
I'm a bit rusty since we learned this, but it cant find the file.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
//declare Vars and constants
double input;
double total = 0.0;
ifstream myfile;
myfile.open ("prices.txt");
if (myfile.is_open())
{
//Enter input
while(myfile.eof() == false)
{
myfile>>input;
total = total + input;
}//end while
total = total/5;
cout << "The Average is : " << total<< "\n";
myfile.close();
}//end if
else
cout << "Error opening file\n";
system("pause");
return 0;
} // end of main funct.
When I run, the average is incorrect. The program gives me the average equal to 31.542
When I calculate the average myself on a calculator I get 28.074. The 5 numbers are
10.5
15.99
20
76.54
17.34
I already have been told that its suppose to be equal to 28.07 but I dont know why the program calculates incorrectly
Don't loop on eof(); loop on good() instead. The eof() isn't set until you've tried and failed to read from the file, so your loop will fail to read in the sixth time. This doesn't change the value of total, so the total gets an extra copy of the last 17.34, which, when divided by 5 gives you the incorrect result of 31.542.