浮点数- c++中的除法和计数问题
floating point - C++ problems with dividing and cout
我正在做计算机科学的作业。我们得做一个击球率的程序。我让它工作,这样它就会计算安打,出局,安打等,但当它要计算打击率时,它会得出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
除以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)()
,因为编译器会在你做错的时候给你更多的提示。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 余数除法和不允许除以零 (c++) 时遇到问题
- 关于使用类型转换优化除法代码的问题
- "Primitive Calculator" - 创建除法循环时出现问题
- C++:循环中的除法问题
- 浮点数- c++中的除法和计数问题
- c++中的除法问题