英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论