打印结果判断题求解

CeleronWind 2003-07-30 11:11:42
题目如下:
8. What results from attempting to compile and run the following code?
public class Ternary{
public static void main(String args[]){
int a = 5;
System.out.println("Value is - " + ((a < 5) ? 9.9 : 9));
}
}
A.print:Value is -9
B.print:Value is -5
C.Compilation error
D.None of these

我的答案是A
标答是D
说明如下:
D is correct. The code compiles successfully. In this code the optional value for the ternary operator, 9.0(a double) and 9(an int) are of different types. The result of a ternary operator must be determined at the compile time, and here the type chosen using the rules of promotion for binary operands, is double. Since the result is a double, the output value is printed in a floating point format. The choice of which value to be printed is made on the basis of the result of the comparison "a < 5" which results in false, hence the variable "a" takes the second of the two possible values, which is 9, but because the result type is promoted to double, the output value is actually written as 9.0, rather than the more obvious 9, hence D is correct.


但是不明白为什么要采用double的格式来显示,哪位详细解释一下?
...全文
61 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Martin2002 2003-08-01
  • 打赏
  • 举报
回复
这个是采用了java的类型转换规则。一般来说 int --> long --> float --> double
而对与byte short类型则采用int来进行计算
jkit 2003-07-31
  • 打赏
  • 举报
回复
说明已经说得很清楚了啊.
简单翻译一下:
在 ?: 运算符编译时, : 两边的数据类型要求一样.
因为9.9和9类型不一样,所以它们要被转化成相同类型, 即double.
CeleronWind 2003-07-31
  • 打赏
  • 举报
回复
还想看看其他人的解释。

51,408

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧