为什么 System.out.print(三元运算符) 在输出中打印浮点数?

Why System.out.print(ternary operator) print float in output?

我正在查看一些 java 面试问题 MCQ,在那里我找到了这个代码片段,虽然它只是一个 2 行代码,但我不理解它的输出。

int a = 8;
System.out.println(((a<8)? 9.9 : (int)9));

输出为 9.0 我不明白为什么不是 9 ?

三元运算符的return类型是根据相当复杂的规则来确定的: Java Language Specification。具体来说,在您的情况下:

Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.

因此在您的情况下,您会得到 return 输入双精度。

三元运算符具有 return 在计算值之前定义的类型。 因此,如果运算符可以 return float 和 int,那么这两个值都会向上转换为 float。 你的答案是这样投的:

(int)9 -> (int)9 -> (float)9.

其他情况:float和int相加得到float

int a = 2;
float b = 4.3f;
float c = a + b;

因为你没有全部投射。你只是将第二个结果转换为 int.

但不要忘记第一个结果是浮点数,所以所有结构必须是同一类型。 您需要将它们全部转换为相同类型,例如 int 或 float。

int a = 8;
System.out.println(""+ (int)( (a<8)? 9.9 :  9));

输出:

9