【发布时间】:2015-07-06 15:00:54
【问题描述】:
我无法理解以下代码如何打印 50.0
public class Pre
{
public static void main(String[] args)
{
int x=10;
System.out.println((x > 10) ? 50.0 : 50); //output 50.0
}
}
它应该打印 50(我猜)而不是 50.0
上面的代码不是和下面的代码是等价的吗,
public class Pre
{
public static void main(String[] args)
{
int x=10;
if(x>10)
System.out.println(50.0);
else
System.out.println(50);//output
}
}
如果它们是等价的,那么为什么输出不同?
【问题讨论】:
-
因为它们不等价。哪里有骗子。
-
@Sotirious-但是在大多数书籍中,都提到第一个代码可以认为是第二个代码
-
@RajMalhotra 是的,它们可以被认为是等价的;但它们并不相同......这是一种用于教初学者的简化,但并不是全部。
-
我不认为这个问题与Why does the ternary operator unexpectedly cast integers? 重复,尽管它们非常相似。这个问题是关于原语的;那个是关于盒装数字的(这更奇怪)
标签: java if-statement int double