微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

条件if-else语句在java

参见英文答案 > Why does the ternary operator unexpectedly cast integers?2
我无法理解下面的代码如何打印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
    }
}

如果他们是等价的,那么为什么产出差异?

解决方法

Java确保您的类型是一致的,所以在第一个语句中
(x > 10) ? 50.0 : 50

你有一个双重的,所以表达式的返回类型是double,并且litteral int被转换为double.所以有条件的双方是一样的!

如果你改变它

System.out.println((x > 10) ? 50.0 : 49);

它打印49.0.

if / else不是表达式,因此它不必进行任何转换.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐