加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

条件if-else语句在java

发布时间:2020-12-14 05:31:29 所属栏目: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 }} 它应该打
参见英文答案 > 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不是表达式,因此它不必进行任何转换.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读