为什么在Java中将整型转换为浮点型?

huangapple go评论74阅读模式
英文:

Why is int being cast to float in java?

问题

在这段代码中:

    public void display(int x, double y){
        System.out.println("Double");
    }
    public void display(int x, float y){
        System.out.println("Float");
    }
    public static void main(String[] args){
        prog01 p = new prog01();
        p.display(4,5); //第一个输出
        p.display(4,5.0); // 第二个输出
    }

输出结果为:

Float
Double

第二个输出结果可以理解,但为什么数字 5 被转换为浮点型(float),而不是产生错误呢?

英文:

In this code

    public void display(int x, double y){
        System.out.println("Double");
    }
    public void display(int x, float y){
        System.out.println("Float");
    }
    public static void main(String[] args){
        prog01 p = new prog01();
        p.display(4,5); //First Output
        p.display(4,5.0); // Second Output
    }

The outputs are:

Float
Double

The second output is understandable, but why is 5 being cast to float when it should have given an error?

答案1

得分: 1

Widening Casting(隐式转换)发生在 byte -> short -> int -> long -> float -> double。在这里,您传递的是整数,因为它没有 long 类型,下一个类型是 float。这就是为什么它给您的是 float

英文:

Widening Casting (Implicit) happens, byte -> short -> int -> long -> float -> double.
Here you pass integer, Since it doesn't have long as a type, the next one is float. That's why it's giving you float

huangapple
  • 本文由 发表于 2020年9月8日 11:14:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63786631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定