[英]Why does double parameterised function accepts float and not vice versa?
I have encountered something strange today.我今天遇到了一些奇怪的事情。 The below code compiles unexpectedly and runs fine.下面的代码意外编译并运行良好。
public class Test {
public static void func(double d) {
System.out.print("d : " + d);
}
public static void main(String[] args) {
float f = 10.0f;
func(f); // output: d : 10.0
}
}
But this one gives compilation error但是这个给出了编译错误
public class Test {
public static void func(float f) {
System.out.print("f : " + f);
}
public static void main(String[] args) {
double d = 10.0d;
func(d);
}
}
Can somebody please explain this behaviour ?有人可以解释这种行为吗?
Type promotion from float
to double
is safe as no data is lost and all float
4 bytes can fit into double
8 byes.从float
到double
类型提升是安全的,因为不会丢失数据,并且所有float
4 字节都可以放入double
8 字节。
However the opposite, from double
to float
, always truncates the data as double
8 bytes can't fit into float
4 bytes.然而相反,从double
到float
,总是截断数据,因为double
8 字节不能适应float
4 字节。 Compiler guards against doing this truncation accidentally by forcing the programmer to manually specify the type conversion.编译器通过强制程序员手动指定类型转换来防止意外进行这种截断。
double
(8 byte) is a bigger data type than float
(4 byte) so you can store float
(4 byte) in double
(8 byte) but you can't double
in float
. double
(8 字节)是比float
(4 字节)更大的数据类型,因此您可以将float
(4 字节)存储在double
(8 字节)中,但不能在float
double
。 If you try to do that you'll get Possible loss of precision
error.如果您尝试这样做,您将获得Possible loss of precision
误差Possible loss of precision
。
So the following will give error.所以下面会报错。
float f = 120.55;
While this one don't虽然这个不
double d = 120.44f;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.