【问题标题】:Why do I have to add a decimal to get this math correct in C++ [duplicate]为什么我必须添加小数才能在 C++ 中正确计算 [重复]
【发布时间】:2018-10-18 06:45:28
【问题描述】:

我正在计算一个球体的体积,经过大量研究后我发现我无法使用:

float sphereRadius = 2.33;
float volSphere = 0;
volSphere = (4/3) * (M_PI) * std::pow(sphereRadius, 3);

但必须添加3.0 才能获得正确答案。

volSphere = (4/3.0) * (M_PI) * std::pow(sphereRadius, 3);

为什么必须添加小数才能得到正确的计算?

【问题讨论】:

  • 查找整数除法...必须是数百个重复项
  • 仅涉及整数的表达式被执行为整数运算并具有整数结果。

标签: c++ division integer-division


【解决方案1】:

(4/3) 是一个integer 除以另一个integer,得到另一个integerinteger 不能是 1.33 或类似的东西,所以它会被截断为 1。对于小数点,您将其改为 double,将 integer 除以 double 得到 double,它支持分数。

【讨论】:

  • s/rounded/truncated/ ;)
  • 哈哈是的,“截断”在这里确实是正确的术语。 “四舍五入”可能会被误解……它实际上从未四舍五入正数。感谢您的提示,我将其添加到答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
  • 2012-01-05
  • 2010-10-03
  • 1970-01-01
相关资源
最近更新 更多