我有这个函数:
enemigo.posZ = 5.1529696E8 //This is the value at runtime, it's a float.
double posicionZ = Math.round(enemigo.posZ*100.0f)/100.0f;
这是输出结果,但为什么?它应该将其四舍五入到整数!
posicionZ = 2.1474836E7
我有这个函数:
enemigo.posZ = 5.1529696E8 //This is the value at runtime, it's a float.
double posicionZ = Math.round(enemigo.posZ*100.0f)/100.0f;
这是输出结果,但为什么?它应该将其四舍五入到整数!
posicionZ = 2.1474836E7
以21474开头并且有很多位数字的整数可能是一个提示!
Java有两个版本的Math.round()
:
public static int Math.round(float a) // float -> 32-bit int
public static long Math.round(double a) // double -> 64-bit long
让我们来看一下代码:
double posicionZ = Math.round(enemigo.posZ * 100.0f) / 100.0f;
由于enemigo.posZ
是一个浮点数,因此使用第一个版本。它想要返回enemigo.posZ * 100.0
,即51529696000.0,作为32位整数,但是它无法完成,因为它溢出了。因此,它返回Integer.MAX_VALUE
,或2^³¹ - 1 = 2147483647。然后除以100.0f得到21474836.0,即2.1474836E7。