我有这样的代码:
System.out.println("Math.round(1423562400L) => " + Math.round(1423562400L));
结果如下:
Math.round(1423562400L) => 1423562368
这个值是一个64位整数,但它可以很容易地放进一个32位整数里面,并且应该适合于double。发生了什么事情?
Math.round(float)
比Math.round(double)
更具体,由于它们都是有效重载, 编译器选择前者,导致数据丢失。1423562400L
更改为1423562400d
。float
版本比double
版本更具体吗?因此,它首先尝试浮点版本,如果编译成功,则使用它。但是为什么首选浮点版本?这在JLS中没有指定。 - swdeverror: call of overloaded 'round(long int)' is ambiguous
。 - swdev我认为 Math.round()
没有支持 long
参数的实现。这是 Math.round()
的签名。
Math.round(double a);
Math.round(float a);
Math.round()
接受 double
或 float
,因此当您传递 long
时,您正在执行类似于 (long
隐式转换为 float) 的操作。
float x = 1423562400L;
System.out.println(Math.round(x));
要解决这个问题,您可以先将long
值加到double
中,它会像魔法一样工作。
double x = 1423562400L;
System.out.println(Math.round(x));
为了简化,你可以这样做
Math.round((double)1423562400L)
或者
Math.round(1423562400d)
long
会被转换为float
。
图片来源 这里
public static int round(float a)
它接受一个32位的浮点数,现在你把一个64位的长整型传入了这个方法, 它会将长整型截断为整型,然后转换成浮点数。
System.out.println(Math.round((int)1423562400L));
System.out.println(Math.round((float)1423562400L));
代码也会打印1423562368
如果你显式地将其转换为double类型,那么结果就是正确的
1423562400
double
重载。人们本可以希望使用它。 - Thilo
(double)
时,它工作正常。显然,否则它是一个float
?! - Thilolong
会自动转换为float
? - swdev