为什么我必须添加一个小数才能使 C++ 中的数学正确

Why do I have to add a decimal to get this math correct in C++

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

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);

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

(4/3) 是一个 integer 除以另一个 integer,结果是另一个 integerinteger 不能是 1.33 或类似的东西,因此它会被截断为 1。对于小数,你告诉它是一个 double 而不是 integer 除以 double 结果 double,它支持分数。