Math.round在android

时间:2015-09-21 10:38:15

标签: java android math

我有这个功能:

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

1 个答案:

答案 0 :(得分:2)

一个有大量数字的整数,以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位int返回,但它不能因为它溢出而返回。所以它返回Integer.MAX_VALUE,或2 ^³¹ - 1 = 2147483647.然后100.0f的divison返回21474836.0,即2.1474836E7。

相关问题