Math.abs()绝对值取到的数不一定是正数

Math.abs()

注释:Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

源码:

public static int abs(int a) {

        return (a < 0) ? -a : a;

    }

解释:只是对负数做了个取反,对于下面这种临界值

实际操作(Integer的最小值操作):

System.out.println(Integer.MIN_VALUE);

System.out.println(Math.abs(Integer.MIN_VALUE));

System.out.println(Math.abs(Integer.MIN_VALUE+1));

结果:

-2147483648

-2147483648

2147483647

实际操作(long值操作,然后强转int):

//= 2的32次方+ Integer.MAX_VALUE + 1 = 二进制的31个0+1+1+31个0

long aaa = new BigDecimal(2).pow(32).longValue() + Integer.MAX_VALUE + 1;

System.out.println(aaa);

System.out.println((int)Math.abs(aaa));

结果:

6442450944

-2147483648

猜你喜欢

转载自xinklabi.iteye.com/blog/2344948