Java int + =双语法惊喜 [英] Java int += double syntax surprise

查看:131
本文介绍了Java int + =双语法惊喜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下令人惊讶的界限:

I have run into the following surprising line:

int x = 7;
x += 0.5;

显然是合法的语法!在添加之后,x仍然是7,因此double被强制转换为int并向下舍入为0,但这在代码中没有任何显式强制转换的情况下完成。有人对此感到惊讶吗?这里的理由是什么?

is apparently legal syntax! After the addition, x is still 7, so the double is being cast to an int and rounded down to 0, but this is done without any explicit cast in the code. Is anyone else surprised by this? What's the rationale here?

编辑以澄清我的问题:任何人都可以给出这个决定的充分理由吗?我觉得这是一个需要在其他地方进行显式投射的可怕决定,但是在你默默抛弃数据的语言中有这一点。我错过了什么吗?

edit to clarify my question: Can anyone give a good reason for this decision? It strikes me as a terrible decision to require explicit casting everywhere else, but have this one spot in the language where you silently throw away data. Am I missing something?

推荐答案

x += 0.5;

相当于:

x = (int) (x + 0.5)

一般来说:

x + = y 相当于 x =(x的类型)(x + y)

参见 15.26.2。复合赋值运算符

这篇关于Java int + =双语法惊喜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆