gpt4 book ai didi

java - 类型转换值(value)和由此产生的数学

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:42:48 24 4
gpt4 key购买 nike

short x, y; 
short z = ((short)x) + ((short)y);

所以我了解到在 Java 中,一个值在相加时被认为是一个整数。这只是语言中的细微差别之一。但是,在这里,我已经将 short 转换为变量 xy 并且它仍然给我一个错误提示

can't convert from int to short

最佳答案

so I understand that in java that a value is considered an integer when it is added.

不一定。如果您要添加 long 则不会s,例如。

However, here, I am already casting short to the variables x and y and it still gives me an error saying that can't convert from int to short.

那是因为您在添加值之前对其进行了转换; +结果仍然是 int . (事实上​​,(short)x 是一个空操作;x已经一个 short 。)

正确的写法是:

short z = (short)(x + y);

short我们晋升为 int s,加在一起,然后我们将结果向下转换为 short .

回复你的评论:

(I'm) not sure why first casting the x and the y to short and putting them into parentheses would not result in short + short addition

因为 Java 没有 short + short添加。它添加的最小尺寸是 int ,因为 the first thing “加法”运算符( +- )做的是 binary numeric promotion :

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    • If either operand is of type double, the other is converted to double.

    • Otherwise, if either operand is of type float, the other is converted tofloat`.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

所以 short + short (或 char + charbyte + byte )变为 int + int屈服 int . Java 的唯一 整数加法是int + int => intlong + long => long .

关于java - 类型转换值(value)和由此产生的数学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32925142/

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