[英]Why does this multiplication integer overflow result in zero?
在回答了這個問題后 ,我很困惑為什么這段代碼中的溢出整數導致0
而不是負數。 這很奇怪,為什么這么准確? 為何0?
public class IntegerOverflow {
public static void main(String[] args) {
int x = 10;
int i = 0;
for (i = 0; i <= 5; i++)
{
x = x * x;
System.out.println(x);
}
}
}
輸出:
100
10000
100000000
1874919424
0
0
x
的起始值是偶數時才會發生這種情況。 根據JLS§15.17.1 :
如果整數乘法溢出,則結果是數學乘積的低階位 ,如某些足夠大的二進制補碼格式所示。 結果,如果發生溢出,則結果的符號可能與兩個操作數值的數學乘積的符號不同。
如果我們以二進制格式而不是十進制格式打印數字,這會更加明顯:
public class IntegerOverflow {
public static void main(String[] args) {
int x = 10;
int i = 0;
for (i = 0; i <= 5; i++)
{
x *= x;
System.out.println(Integer.toBinaryString(x));
}
}
}
輸出:
1100100
10011100010000
101111101011110000100000000
1101111110000010000000000000000
0
0
如您所見,每次平方時,我們將零位數加倍。 由於只保存了低位,因此每次將零加倍最終將導致零。 請注意,如果x
的起始值為奇數, 則不會看到這些尾隨零 。 相反,它會導致看似無關的數字,如溢出通常會產生。
public class IntegerOverflow {
public static void main(String[] args) {
int x = 11;
int i = 0;
for (i = 0; i <= 5; i++)
{
x *= x;
System.out.format("%-12d\t%s%n", x, Integer.toBinaryString(x));
}
}
}
輸出:
121 1111001
14641 11100100110001
214358881 1100110001101101101101100001
772479681 101110000010110001101011000001
-1419655807 10101011011000011100010110000001
-1709061375 10011010001000011100101100000001
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.