Hi all,
I am having problem about file operations. There are a few numbers in my txt file. I want the program to calculate average of these numbers in the txt file. The code I have written is as below. Number of numbers in the file is 5. When I return count it returns 5 .The sum of numbers should be 92 but I get 94, and I get average 18.8 but the correct average should be 18,4 (txt file is attached). So can anyone help me about it? Do you think is it a good idea to calculate it in this way?
Thanks
the code:
int main()
{
ifstream fin;
fin.open("numbers.txt");
if (fin.fail())
{
cout << "erorr on opening the file \n";
exit (1);
}
cout << "the caculated average is " << avg_file(fin) << endl;
double calculated_avg = avg_file(fin);
}
double avg_file(ifstream& source_file)
{
double number_in_file;
double total = 0;
int count = 0;
source_file >> number_in_file;
while (! source_file.eof())
{
source_file >> number_in_file;
total = number_in_file + total;
count ++;
}
//average of numbers in file
return (count);
}