为什么是 1.2 * 30 = 35?
为什么会这样:
int main(void)
{
short w = 30;
return 1.2 * w;
}
返回 35?
Why does this:
int main(void)
{
short w = 30;
return 1.2 * w;
}
return 35?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
1.2 * w
为36.0
。它具有双精度类型,这意味着它不能准确表示。它可能会略小于
36
,也可能是35.99999
,因此当您返回它时,小数部分将被丢弃,仅返回整数部分。这就是您获得35
的方式。PS 所有浮点运算都不精确。您应该预计会有很小的差异。此外,当您将浮点值与固定值进行比较时,不得进行直接比较,而应进行范围比较。
错误:
if (value == 36.0) { /* ... */ }
正确:
if (abs (value - 36.0) < 0.0001) { /* ... */ }
1.2 * w
is36.0
. It has the double type meaning it is not represented exactly.Likely it turns out to be slightly less than
36
, maybe35.99999
so when you return it the fractional part is discarded and the integer part only is returned. That's how you get35
.P.S. All operations with floating point are not precise. You should expect little discrepancies. Also when you compare a floating point value against a fixed value, you mustn't do a direct comparison but do a range comparison.
Wrong:
if (value == 36.0) { /* ... */ }
Correct:
if (abs (value - 36.0) < 0.0001) { /* ... */ }
这是二进制浮点精度的问题。
1.2
比 1.2 略小,因此相乘的结果略小于 36。It's an issue with binary floating point precision.
1.2
is very slightly less than 1.2, so the result of the multiplication is slightly less than 36.由于表示形式:1.2 实际上类似于 1.1999999
Because of representation: 1.2 is really something like 1.1999999
由于浮点数学可能不精确,因此在转换为整数之前使用
round()
,以获得更好的结果。Since floating point math could be inexact, use
round()
before casting to integer, to get a better result.不要期望浮点运算有绝对精确的结果。例如,相乘结果可以是 35.9999,四舍五入为 35。
Don't expect absolutely exact result in floating point operations. Multiplication result may be, for example, 35.9999, which is rounded to 35.
短w = 30;
返回 1.2 * w;
在 return 语句中,第一个排序值是 double 类型,因为 1.2 是 double 类型
所以它将乘以 1.2 * 30.000000
结果变为 35.999999 左右,函数返回类型为 int,因此小数部分被截断,仅返回 35。
short w = 30;
return 1.2 * w;
In return statement first sort value is type cast in double because 1.2 is double type
so it will multiply 1.2 * 30.000000
and result become around 35.999999 and function return type is int so decimal part is truncate and it return 35 only.
如果您想获得更合适的结果,请尝试以下操作:
If you want to get more suitable result, try the following: