問題描述
考慮一下 Java 語言規范中的這段代碼.
Consider this snippet from the Java language specification.
class Test {
public static void main(String[] args) {
int i = 1000000;
System.out.println(i * i);
long l = i;
System.out.println(l * l);
}
}
輸出是
-727379968
1000000000000
為什么 (i*i)
的結果是 -727379968
?理想情況下應該是 1000000000000.
Why is the result -727379968
for (i*i)
? Ideally it should be 1000000000000.
我知道 Integer 的范圍是從 –2147483648 到 2147483647.所以顯然 1000000000000不在給定范圍內.
I know the range of Integer is from –2147483648 to 2147483647. so obviously 1000000000000 is not in the given range.
為什么結果會變成-727379968
?
推薦答案
Java(就像現在的大多數計算機架構一樣)使用一種叫做 二進制補碼算法,它使用整數的最高有效位來表示一個數字是否為負數.如果你將兩個大數相乘,你會得到一個大到設置最高位的數,結果是負數.
Java (like most computer architectures these days) uses something called two's complement arithmetic, which uses the most significant bit of an integer to signify that a number is negative. If you multiply two big numbers, you end up with a number that's so big it sets that highest bit, and the result ends up negative.
這篇關于兩個整數相乘溢出導致負數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!