3 回答

TA貢獻1790條經驗 獲得超9個贊
java中int的最大值是2,147,483,647將19加到j上,一次又一次,這個值會被傳遞。之后它將再次從 int 的最小值開始,即-2,147,483,648。
這將一直持續到 j 的值在某個時刻變為 1000。因此,循環將停止。
j將在整數的最大值上迭代 17 次以達到這一點。檢查代碼:
public class Solution {
public static void main(String args[]) {
int j = 0;
int iterationCount = 0;
for(int i=0;j != 1000;i++) {
j = j+19;
if(j - 19 > 0 && j < 0) {
iterationCount ++;
}
}
System.out.println("The value of J is: " + j + " iterationCount: " + iterationCount);
}
}
輸出:
The value of J is: 1000 iterationCount: 17

TA貢獻1789條經驗 獲得超8個贊
像這樣掃描溢出:
public static void main(String[] args) {
int j = 0;
for(int i=0;j != 1000;i++) {
j = j+19;
if(j < Integer.MIN_VALUE+19){
System.out.println("overflow");
}
}
System.out.println("The value of J is: " + j);
}
印刷
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
溢出
J的值為:1000
這意味著 j 溢出 17 次,直到增量 19 最終達到 1000。

TA貢獻1827條經驗 獲得超8個贊
正如 Saheb 所說,這是由于整數溢出造成的。
在 3842865528 次迭代后達到 J 的值 1000
public static void loop2()
{
int j = 0;
long iterations = 0;
for (int i = 0; j != 1000; i++) {
j = j + 19;
iterations++;
}
System.out.println("The value of J is: " + j + " reached after " + iterations + " iterations");
}
添加回答
舉報