1

我正在做计算机科学的作业。我们必须制定一个击球率计划。我让它工作,以便它可以计算安打、出局、单打等,但是当它计算击球率时,它会得到 0.000。我不知道为什么,我已经进行了大量的谷歌搜索,尝试将变量设为 double 和 float 等。这是代码:

#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。提前致谢!!!

4

2 回答 2

4

您正在执行整数除法。将至少一个操作数显式转换为double. 例如:

battingAverage = (static_cast<float>(hits) / (timesBatted - walks));

分配给sluggingPercentage.

于 2013-03-06T15:39:49.383 回答
0

简单的除以intanint就是 another int。只需投一个到double.

例如,

battingAverage = static_cast<double>(hits) / (timesBatted - walks)
sluggingPercentage = static_cast<double>(singles + doubles * 2 + triples * 3 + homeRuns*4) / (timesBatted - walks)

始终使用 C++ casts ( static_cast<double>()) 而不是 C casts (double)(),因为编译器会在您做错事时为您提供更多提示。

PS 不要讨厌 C++!:( 给它一点爱,它会爱你!

于 2013-03-06T15:40:17.017 回答