我需要一个帮助学校的项目。我们必须编写一个程序,向用户询问关于棒球运动员的信息。我们需要计算玩家的击球平均数,击球次数和命中次数。我遇到了一个问题,即我的平均计算结果是输出一个集合数并且没有执行任何计算。我输入用于计算的所有变量的整数。所以我会输入数字如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. :-) –