Math.abs为Integer.Min_VALUE返回错误的值 [英] Math.abs returns wrong value for Integer.Min_VALUE

查看:226
本文介绍了Math.abs为Integer.Min_VALUE返回错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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

返回 -2147483648

它是否应该返回绝对值 2147483648

Should it not return the absolute value as 2147483648 ?

推荐答案

Integer.MIN_VALUE -2147483648 ,但最高值为32位整数可以包含 +2147483647 。试图在32位int中表示 +2147483648 将有效地翻转到 -2147483648 。这是因为,当使用有符号整数时, +2147483648 -2147483648 的二进制补码表示相同。但是,这不是问题,因为 +2147483648 被视为超出范围。

Integer.MIN_VALUE is -2147483648, but the highest value a 32 bit integer can contain is +2147483647. Attempting to represent +2147483648 in a 32 bit int will effectively "roll over" to -2147483648. This is because, when using signed integers, the two's complement binary representations of +2147483648 and -2147483648 are identical. This is not a problem, however, as +2147483648 is considered out of range.

稍微阅读一点在这个问题上,你可能想查看维基百科有关二补的文章

For a little more reading on this matter, you might want to check out the Wikipedia article on Two's complement.

这篇关于Math.abs为Integer.Min_VALUE返回错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆