John John - 1 year ago 72
C++ Question

finding the average of sums made in a loop in c++

Hello everyone I'm trying to find the average of a random amount of numbers that are input into a loop. For sum reason after the loop im able to print the right total, but when i try to find the average i get a weird answer. can anyone help me with this or direct to a thread on here that could help? I wasnt able to find anything on here.

here is my code for the program that isnt working.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
ifstream inData;
string golferFile;
string golfer;
int matches;
int score;

cout << endl;
cout << "Enter the golfer's filename: ";
cin >> golferFile;;
getline(inData, golfer);
inData >> matches;
cout << endl;
cout << "The golfer " << golfer << " has " << matches << " matches with scores"
" of" << endl;
cout << endl;
int count;
count = 1;
int matchNumber;
matchNumber = 1;
int sum;
while(count <= matches)
inData >> score;
cout << "Match " << matchNumber << ": " << score << endl;
sum = sum + score;
int mean;
mean = sum / matches;
cout << "The mean score is " << mean << endl;
return 0;

the output i receive is this for the mean

The mean score is 1399255

Answer Source

I found several error in your code.

  • you forget to initialize your sum variable.
  • in while loop an extra brace found.remove it
  • you didn't write anything to stop your loop.that why your loop run infinite initialize you loop also.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download