问题描述
此代码:
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返回错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!