Hello all, I am working on an assignment and came across a problem.
The assignment is to take a file with integers and calculate the average. Here is my code:

#include <iostream>
#include <fstream>
#include <stdlib>
#include <conio.h>

double calculateAverage(double Number, double Sum);
void trimSpaces(char Filename[]);

int main()
{
	ifstream InputStream;
   double Numbers = 0;              // Number of Numbers
   double Total = 0;                // Sum of all numbers
   double n;                        // Temp variable
   double Average;
	char FileName[30];

   cout << "Enter file name. ";
   cin >> FileName;

   InputStream.open(FileName);
	if (InputStream.fail())
   {
   	cout << "Error opening file.";    // Error
		getch();
      exit(1);
   }

   while (!InputStream.eof())
   {
   
      InputStream >> n;
      Total += n;
   
      cout << "\nCurrent sum: " << Total;
      Numbers++;
   }

	Average = calculateAverage(Numbers, Total);

   cout << "\n\nAverage: " << Average;

	getch();
}

double calculateAverage(double Number, double Sum)
{
   return (Number * 1.0) / Sum;
}

The file I am using contains, "1 5 7 2 5", so the answer should be 4. Instead, the program adds the last number "5" twice and gives me a totally different answer. Any ideas?

Recommended Answers

All 3 Replies

double calculateAverage(double Number, double Sum)
{
return (Number * 1.0) / Sum;
}

You have to divide Sum by Number , not the Number by sum.

>>the program adds the last number "5" twice

That's because you are wrote the loop incorrectly. Do it like this:

while ( InputStream >> n )
{
   // blabla
}

Thanks, guys! It worked!

~Mr. Doughnuts

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.