gpt4 book ai didi

java - 为什么我的数据类型没有自动提升为 Double

转载 作者:行者123 更新时间:2023-12-01 17:20:03 26 4
gpt4 key购买 nike

我知道某个数据类型会自动提升为上层数据类型字节短整型

class Temp {
void check(byte x) {
System.out.println(x + " is the byte type");
}

void check(short x) {
System.out.println(x + " is the short type");
}

void check(int x) {
System.out.println(x + " is the int type");
int y = x;
System.out.println(y + " is the int type");
}

void check(long x) {
System.out.println(x + " is the long type");
}

void check(float x) {
System.out.println(x + " is the float type");
}

void check(double x) {
System.out.println(x + " is the double type");
}

public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result =" + result);
Temp t = new Temp();
t.check(f * b);
t.check(i / c);
t.check(d * s);
t.check(b + b);
t.check(b * b);
t.check(b * b * b);
t.check(b * b * b * b * b * b * b * b * b);
t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b * b * b * b * b * b * b * b * b * b * b);
t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b);

}
}

输出:

238.14 + 515 - 126.3616
result =626.7784146484375
238.14 is the float type
515 is the int type
515 is the int type
126.3616 is the double type
84 is the int type
84 is the int type
1764 is the int type
1764 is the int type
74088 is the int type
74088 is the int type
-1889539584 is the int type
-1889539584 is the int type
-2147483648 is the int type
-2147483648 is the int type
0 is the int type
0 is the int type

我的问题是为什么 b*b 提升为 int 因为 42+42=84 且字节范围是 -128 到 127。84 在范围内。此外,为什么

t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b * b * b * b * b * b * b * b * b * b * b);

这一行得到了 0 为什么不将其提升一倍。

最佳答案

my question is that why b*b promote to int

因为这就是语言规范所说的。

and why [...] this line got 0 why not promote to that double

再说一遍,因为这不是语言的定义方式。

阅读section 15.17 of the JLS :

The multiplicative operators have the same precedence and are syntactically left-associative (they group left-to-right).

The type of each of the operands of a multiplicative operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

Binary numeric promotion is performed on the operands (§5.6.2).

二进制数字提升 ( 5.6.2 ) 将提升 byte操作数为 int ,所以你最终得到 int * int代码中所有情况下的算术。在第一种情况下,你有 byte * byte所以两个操作数都提升为 int ;对于长长的队伍,你有一个 byte * byte其余的是int * byte ,其中只有第二个操作数被提升为 int 。该选择是在编译时做出的,与执行时的值无关 - JVM 不会决定将值提升为 double因为它们溢出了 int 的边界.

关于java - 为什么我的数据类型没有自动提升为 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19412559/

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