Viv*_*mar 9 java double int if-statement
我无法理解下面的代码如何打印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
}
}
Run Code Online (Sandbox Code Playgroud)
它应该打印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
}
}
Run Code Online (Sandbox Code Playgroud)
如果它们是等价的,那么为什么输出的差异呢?
Java确保您的类型是连贯的,因此在第一个语句中
(x > 10) ? 50.0 : 50
Run Code Online (Sandbox Code Playgroud)
你有一个双重优先,所以表达式的返回类型是double,而litteral int则转换为double.因此条件的两边是相同的!
如果你改成它
System.out.println((x > 10) ? 50.0 : 49);
Run Code Online (Sandbox Code Playgroud)
它打印49.0.
if/else不是表达式,因此它不必进行任何转换.
它打印50.0因为在第一种情况下你正在调用OutputStream.println(double)方法,因为你的第一个表达式返回的double是你的条件.
但在第二种情况下,你正在调用OutputStream.println(int)方法.
三元条件运算符的类型 - (x > 10) ? 50.0 : 50)由第2和第3个操作数确定.在你的情况下,它必须能同时包含的价值观50.0和50,因此其类型double.
因此,即使表达式返回50,它也会被转换为double,你看50.0.
如果你改变了
System.out.println((x > 10) ? 50.0 : 50);
Run Code Online (Sandbox Code Playgroud)
至
System.out.println((x > 10) ? 50.0 : 10);
Run Code Online (Sandbox Code Playgroud)
你会看到10.0打印,这将显然:返回正确的值(右侧).
| 归档时间: |
|
| 查看次数: |
716 次 |
| 最近记录: |