`
xinklabi
  • 浏览: 1560491 次
  • 性别: Icon_minigender_1
  • 来自: 吉林
文章分类
社区版块
存档分类
最新评论

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics