0
大家好,我試圖找到輸入到循環中的隨機數量的平均值。爲了總和的原因後循環能夠打印正確的總數,但當我試圖找到平均我得到一個奇怪的答案。任何人都可以幫助我或直接在這裏可以幫助的線程?我無法在這裏找到任何東西。在C++中找到一個循環中的平均數
這裏是我的程序不工作的代碼。
#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
你會介意初始化sum變量嗎? –
我必須在循環之前將它初始化爲零嗎?我剛剛在循環中初始化了,現在是 – John
是的,用零外循環初始化它。 –