不同的行为可能会导致精度损失
在 Java 中,当你这样做时
int b = 0;
b = b + 1.0;
,你可能会遇到精度损失错误。但为什么如果你这么做了
int b = 0;
b += 1.0;
却没有任何错误呢?
In Java, when you do
int b = 0;
b = b + 1.0;
You get a possible loss of precision error. But why is it that if you do
int b = 0;
b += 1.0;
There isn't any error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
b += 1.0;
相当于b = (int) ((b) + (1.0));
。 缩小原始转换 (JLS 5.1 .3)隐藏在复合赋值操作中。JLS 15.26.2 复合赋值运算符(JLS 第三版):
这也解释了为什么以下代码可以编译:
但这并不' t:
在这种情况下,您需要显式强制转换:
值得注意的是,复合赋值中的隐式强制转换是《Puzzle 9: Tweedledum》的主题,来自精彩的书 Java Puzzlers。以下是本书的一些摘录(为简洁起见,略有编辑):
最后一段值得注意:C# 在这方面要严格得多(请参阅 C# 语言规范 7.13.2 复合赋值)。
That's because
b += 1.0;
is equivalent tob = (int) ((b) + (1.0));
. The narrowing primitive conversion (JLS 5.1.3) is hidden in the compound assignment operation.JLS 15.26.2 Compound Assignment Operators (JLS Third Edition):
This also explains why the following code compiles:
But this doesn't:
You need to explicitly cast in this case:
It's worth noting that the implicit cast in compound assignments is the subject of Puzzle 9: Tweedledum from the wonderful book Java Puzzlers. Here are some excerpt from the book (slightly edited for brevity):
The last paragraph is worth noting: C# is a lot more strict in this regard (see C# Language Specification 7.13.2 Compound assignment).