我正在为计算机科学任务。我们必须制定击球平均计划。我有它的工作,它将计算击中,出局,单打等,但当涉及到计算击球率时,它会提高0.000。我不知道为什么,我做了大量的谷歌搜索,尝试使变量双和浮动等,这里是代码:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main(){
const int MAX_TIMES_AT_BAT = 1000;
int hits = 0, timesBatted = 0, outs = 0, walks = 0, singles = 0, doubles = 0, triples = 0, homeRuns = 0;
float battingAverage = 0.0, sluggingPercentage = 0.0;
for(int i = 0; i < MAX_TIMES_AT_BAT; i++){
int random = rand() % 100 +1;
if(random > 0 && random <= 35){
outs++;
}else if(random > 35 && random <= 51){
walks++;
}else if(random > 51 && random <= 71){
singles++;
hits++;
}else if(random > 71 && random <= 86){
doubles++;
hits++;
}else if(random > 86 && random <= 95){
triples++;
hits++;
}else if(random > 95 && random <= 100){
homeRuns++;
hits++;
}else{
cout << "ERROR WITH TESTING RANDOM!!!";
return(0);
}
timesBatted++;
}
cout << timesBatted << " " << hits << " " << outs << " " << walks << " " << singles << " " << doubles << " " << triples << " " << homeRuns << endl;
battingAverage = (hits / (timesBatted - walks));
sluggingPercentage = (singles + doubles * 2 + triples * 3 + homeRuns*4) / (timesBatted - walks);
cout << fixed << setprecision(3) << "Batting Average: " << battingAverage << "\nSlugging Percentage: " << sluggingPercentage << endl;
return 0;
}
任何帮助都会很棒!怎么了?我计算了它,击球率应该是0.5646,击球率应该是1.0937。它的显示是0.0000和1.0000。在此先感谢!!!
答案 0 :(得分:4)
您正在执行整数除法。将至少一个操作数显式地转换为double
。例如:
battingAverage = (static_cast<float>(hits) / (timesBatted - walks));
sluggingPercentage
的作业相同。
答案 1 :(得分:0)
简单地将int
除以int
是另一个int
。只需将其中一个投放到double
。
例如,
battingAverage = static_cast<double>(hits) / (timesBatted - walks)
sluggingPercentage = static_cast<double>(singles + doubles * 2 + triples * 3 + homeRuns*4) / (timesBatted - walks)
始终使用C ++强制转换(static_cast<double>()
)而不是C强制转换(double)()
,因为编译器会为您提供有关何时出错的更多提示。
PS不要讨厌C ++! :(显示它有点爱,它会爱你回来!