我需要一個幫助學校的項目。我們必須編寫一個程序,向用戶詢問關於棒球運動員的信息。我們需要計算玩家的擊球平均數,擊球次數和命中次數。我遇到了一個問題,即我的平均計算結果是輸出一個集合數並且沒有執行任何計算。我輸入用於計算的所有變量的整數。所以我會輸入數字如1,4,10等......由於該程序的價值,我的公式設置自己等於15903.876。我用於平均公式的所有變量均被聲明爲整數,而擊球平均本身被聲明爲雙精度。我已經做了一些自我調試,並發現當它將蝙蝠的次數除以命中次數時,計算會產生混亂。如果有人能幫我弄清楚這個問題,我會很感激。棒球擊球平均項目
//libaries
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class battingAverage
{
public:
string pName;
int nBats;
int tHits;
int gPlayed;
int gcalled;
double average;
double average1;
double playeraverage;
};
int main()
{
string numberPlayers;
int nplayers;
//enters the number of players the user wants to enter data for
cout << "Enter the number of players you want to enter data for: ";
cin >> numberPlayers;
cout << endl;
//converts the value of numberPlayers to nplayers
istringstream convert(numberPlayers);
//sets integer nplayers equal to the value of the string numberPlayers
if(! (istringstream(numberPlayers) >> nplayers))
{
nplayers = 0;
}
cout << "This program calculates the batting average of baseball players.\nYou may enter data for " << nplayers << " players." << endl;
battingAverage ba[nplayers];
int index = 0;
//while statement to get data
while(index < nplayers)
{
cout << "Enter the players last name: " << endl;
cin >> ba[index].pName;
cout << "Enter the number of games the player played: " << endl;
cin >> ba[index].gPlayed;
cout << ba[index].gPlayed << endl;
cout << "Enter the number of games the player was called in for: " << endl;
cin >> ba[index].gcalled;
cout << ba[index].gcalled << endl;
cout << "Enter the number of times the player was at bat: " << endl;
cin >> ba[index].nBats;
cout << ba[index].nBats << endl;
cout << "Enter the number of time the player hit: " << endl;
cin >> ba[index].tHits;
cout << ba[index].tHits << endl;
if(ba[index].tHits > ba[index].nBats)
{
cout << "Enter a valid value for the number of times the player hit: ";
cin >> ba[index].tHits;
}
cout << endl;
index++;
}
//rounds average to 3 decimal places
cout << fixed << setprecision(3);
//average formula
ba[index].playeraverage = (ba[index].nBats/ba[index].tHits) * (ba[index].gPlayed/ba[index].gcalled);//error
cout << ba[index].playeraverage << endl << endl;//just temp line to check calculation of average.
ba[index].average = .000;
ba[index].average1 = .099;
while(ba[index].average < 1 && ba[index].average1 < .899)
{
ba[index].average +=.100;
ba[index].average1 += .1;
//prints chart
cout << setprecision(1) << ba[index].average << "00" << setprecision(3) << setw(12) << ba[index].average1 << endl;
}
cout << "1.000" << setw(12) << "1.000" << endl;
//version of system pause
cout << "\nPress enter to continue...";
cin.sync();
cin.ignore();
return 0;
}
描述什麼是「怪異的數字」。你給你的程序輸入了什麼?你期望輸出什麼? – abelenky
我有一個dejavue。 – user1810087
你在做整數除法。做浮點,你會沒事的。在整數除法中,smaller_number/greater_number總是= 0。換句話說,如果你不打擊1000,那麼你的打擊爲0. :-) –