gpt4 book ai didi

Java Puzzler - 将 double 转换为 int

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:12 25 4
gpt4 key购买 nike

int anInt = 1;
double aDouble = 2.5;

anInt = anInt + aDouble; // Error - need to cast double to int

anInt += aDouble; // This is ok. Why?

anInt = aDouble; // This is also an error.

anInt = 1 + aDouble; // This is also an error.

所以我的问题是:为什么执行 anInt += aDouble 不是编译错误?

最佳答案

四种情况中的三种正确报告错误。复合赋值是该规则的唯一异常(exception)。 Java 语言规范第 15.26.2 部分解释了原因:

15.26.2 Compound Assignment Operators

A compound assignment expression of the form E1 op= E2 is equivalent to E1
= (T) ((E1) op (E2))
, where T is the type of E1, except that E1 is evaluated only once.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

如您所见,通过隐式插入强制转换避免了错误。

关于Java Puzzler - 将 double 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28833590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com