0

my calculations are off in c++ program. The homework assignment is:

"Write a program that reads all the number in the "Random.txt" file and calculates the following:

a. The number of numbers is the file (the final count) b. The sum of all the numbers in the file (total) c. The average of all the numbers in the file (total/count)

Your program should then display the number of numbers found in the file, the sum of the numbers, and the average of the numbers."

Correct sum is 105,527, I get 106,042 Correct average is 528 (if rounded), I get 530

#include <iostream>
#include <fstream>

using namespace std;

int main() 
{

ifstream inputFile;

inputFile.open("/Users/KJVeliz/Desktop/Random.txt");
double num, totalCount, avg;
totalCount = 0;

int count = -1;
while (!inputFile.eof())

    {
        inputFile >> num;
        count++;

        totalCount += num; 
        avg = totalCount / count;

     }

cout << "The number of numbers in the file is: " << count << endl;

cout <<"The sum of the numbers is: " << totalCount << endl;

cout << "The average of the numbers is: " << avg << endl;

return 0;

}

Any help you can offer as to why my calculations are not matching up is much appreciated. I am new to the programming world, so if your answers could be in as much plain English as possible, that would help.

kveliz
  • 11
  • 2
  • 1
    plain english: Learn To Use Your Debugger – pm100 Apr 18 '18 at 18:20
  • Have you verified that the desired sum and average are actually correct? Why are you starting with `count = -1` instead of `0`? – Nico Schertler Apr 18 '18 at 18:26
  • Use the debugger, Luke. – Martin Véronneau Apr 18 '18 at 18:26
  • @nico I know the file has 200 lines of numbers. int count = 0, I always came up with 201. – kveliz Apr 18 '18 at 18:32
  • Then this is definitely a possible error source. `-1` does not make sense. Maybe, the stream is reading something at the end or beginning of the file that is not supposed to be read. Or one line contains two numbers separated by some other character. – Nico Schertler Apr 18 '18 at 18:38
  • `while (!inputFile.eof())` does not do what you think it does . https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – pm100 Apr 18 '18 at 19:22
  • @pm100 Thank you! Using while (inputFile >> num) instead worked. – kveliz Apr 18 '18 at 19:56

0 Answers0