問題描述
考慮一下 Java 語言規(guī)范中的這段代碼.
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)
的結(jié)果是 -727379968
?理想情況下應(yīng)該是 1000000000000.
Why is the result -727379968
for (i*i)
? Ideally it should be 1000000000000.
我知道 Integer 的范圍是從 –2147483648 到 2147483647.所以顯然 1000000000000不在給定范圍內(nèi).
I know the range of Integer is from –2147483648 to 2147483647. so obviously 1000000000000 is not in the given range.
為什么結(jié)果會變成-727379968
?
推薦答案
Java(就像現(xiàn)在的大多數(shù)計算機架構(gòu)一樣)使用一種叫做 二進制補碼算法,它使用整數(shù)的最高有效位來表示一個數(shù)字是否為負數(shù).如果你將兩個大數(shù)相乘,你會得到一個大到設(shè)置最高位的數(shù),結(jié)果是負數(shù).
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.
這篇關(guān)于兩個整數(shù)相乘溢出導(dǎo)致負數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!