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);
}
Attachments
10.00
20.00
40.00
10.00
12.00
4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by firstPerson
double avg_file(ifstream& source_file)
{
double number_in_file;
double total = 0;
int count = 0;
while (source_file >> number_in_file)
{
total = number_in_file + total;
count ++;
}
//average of numbers in file
return (count);
}

http://www.daniweb.com/forums/post155265.html#post155265

Two things:
First, you forgot to add the first number to the total.
Second, with while(!source_file.eof()) you run through the last line twice.

10+20+40+10+12 = 92
you get
20+40+10+12+12 = 94

Thanks for helps. Can you tell me how can I fix it?

Thanks for helps. Can you tell me how can I fix it?

double avg_file(ifstream& source_file)
{
double number_in_file;
double total = 0;
int count = 0;
while (source_file >> number_in_file)
{
total = number_in_file + total;
count ++;
}
//average of numbers in file
return (count);
}

http://www.daniweb.com/forums/post155265.html#post155265

Pay attention.