简体   繁体   English

为什么 System.out.print(ternary operator) 在输出中打印浮点数?

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

I was going through some java interview questions MCQ where I found this code snippet, of which I didn't understand the output, though its only a 2 line code.我正在通过一些 Java 面试问题 MCQ,在那里我找到了这个代码片段,我不理解其中的输出,尽管它只有 2 行代码。

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

Output is 9.0 I didn't understand why it is not 9 ?输出是 9.0 我不明白为什么不是 9 ?

Ternary operator has return type that is defined before the calculation of the value.三元运算符具有在计算值之前定义的返回类型。 So, if the operator can return both float and int, then the both values are upcasted to the float.因此,如果运算符可以同时返回 float 和 int,则这两个值都将向上转换为 float。 Your answer is casted in this way:你的答案是这样投射的:

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

Other situation: If you add float and int, you get float其他情况:如果你加上 float 和 int,你会得到 float

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

The return type of the ternary operator is determined according to quite complicated rules: Java Language Specification .三元运算符的返回类型是根据相当复杂的规则确定的: Java 语言规范 Specifically, in your case:具体来说,就您而言:

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.否则,将二进制数值提升(第 5.6.2 节)应用于操作数类型,条件表达式的类型是第二个和第三个操作数的提升类型。

So in your case you get return type double.因此,在您的情况下,您会得到双倍的返回类型。

Because you are not casting all of them .因为你没有铸造所有的。 you are just casting second result to int.您只是将第二个结果转换为 int。

But don't forget first result is float so all of structure must be same type.但是不要忘记第一个结果是 float 所以所有的结构都必须是相同的类型。 You need to cast all of them as same type like int or float.您需要将它们全部转换为 int 或 float 等相同类型。

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

output :输出 :

9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM