!= Java for 循环中的运算符

下面的代码怎么会打印“J 的值是:1000”?

我会认为“j != 1000”在所有情况下都会评估为假(因为 1000 mod 19 不是 0),因此使其成为无限循环。


public static void loop2() {

    int j = 0;


    for(int i=0;j != 1000;i++) {

        j = j+19;

    }

    System.out.println("The value of J is: " + j);

}


DIEA
浏览 155回答 3
3回答

富国沪深

java中int的最大值是2,147,483,647将19加到j上,一次又一次,这个值会被传递。之后它将再次从 int 的最小值开始,即-2,147,483,648。这将一直持续到 j 的值在某个时刻变为 1000。因此,循环将停止。j将在整数的最大值上迭代 17 次以达到这一点。检查代码:public class Solution {&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; int j = 0;&nbsp; &nbsp; &nbsp; &nbsp; int iterationCount = 0;&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;j != 1000;i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j = j+19;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(j - 19 > 0 && j < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; iterationCount ++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("The value of J is: " + j + " iterationCount: " + iterationCount);&nbsp; &nbsp; }}输出:The value of J is: 1000 iterationCount: 17

拉丁的传说

像这样扫描溢出:public static void main(String[] args) {&nbsp; int j = 0;&nbsp; for(int i=0;j != 1000;i++) {&nbsp; &nbsp; j = j+19;&nbsp; &nbsp; if(j < Integer.MIN_VALUE+19){&nbsp; &nbsp; &nbsp; System.out.println("overflow");&nbsp; &nbsp; }&nbsp; }&nbsp; System.out.println("The value of J is: " + j);}印刷溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出溢出J的值为:1000这意味着 j 溢出 17 次,直到增量 19 最终达到 1000。

慕仙森

正如 Saheb 所说,这是由于整数溢出造成的。在 3842865528 次迭代后达到 J 的值 1000public static void loop2(){&nbsp; &nbsp; int j = 0;&nbsp; &nbsp; long iterations = 0;&nbsp; &nbsp; for (int i = 0; j != 1000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; j = j + 19;&nbsp; &nbsp; &nbsp; &nbsp; iterations++;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("The value of J is: " + j + " reached after " + iterations + " iterations");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java