在c ++中查找循环中的总和的平均值

时间:2016-11-09 06:45:19

标签: c++ loops mean

大家好,我试图找到输入到循环中的随机数量的平均值。为了总结原因循环后我能够打印正确的总数,但当我试图找到平均值我得到一个奇怪的答案。任何人都可以帮我这个或直接到这里的线程可以帮助?我在这里找不到任何东西。

这是我的程序代码,它不起作用。

#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;
inData.open(golferFile.c_str());
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;
     matchNumber++;
     count++;
     sum = sum + score;
   }
  }
int mean;
mean = sum / matches;
cout << "The mean score is " << mean << endl;
return 0;
}

我收到的输出是平均值

平均分为1399255

1 个答案:

答案 0 :(得分:0)

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 time.so initialize you loop also.