浮点数- c++中的除法和计数问题

floating point - C++ problems with dividing and cout

本文关键字:问题 除法 c++ 浮点数      更新时间:2023-10-16

我正在做计算机科学的作业。我们得做一个击球率的程序。我让它工作,这样它就会计算安打,出局,安打等,但当它要计算打击率时,它会得出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。提前感谢!!

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

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

sluggingPercentage的赋值也是如此

简单如int除以intint。只需将一个强制转换为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)(),因为编译器会在你做错的时候给你更多的提示。

不要讨厌c++ !给它一点爱,它也会爱你的!