[英]C++ problems with dividing and cout
我正在做計算機科學的任務。 我們必須制定擊球平均計划。 我有它的工作,它將計算擊中,出局,單打等,但當涉及到計算擊球率時,它會提高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。 提前致謝!!!
您正在執行整數除法。 將至少一個操作數顯式地轉換為double
。 例如:
battingAverage = (static_cast<float>(hits) / (timesBatted - walks));
對sluggingPercentage
的任務也是如此。
簡單地將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 ++! :(顯示它有點愛,它會愛你回來!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.