【问题标题】:!= operator in Java for loop!= Java for 循环中的运算符
【发布时间】:2018-09-11 09:35:34
【问题描述】:

为什么下面的代码会打印“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);
}

【问题讨论】:

  • 我想在某些时候你会溢出 int - 然后你得到的值可能会变成 1000。

标签: java loops for-loop


【解决方案1】:

java中int的最大值是2,147,483,647在j上加19,一次又一次,这个值会被传递。之后它将从 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

【讨论】:

  • 作为旁注,它会在达到 1000 之前溢出并再次循环约 17 次。
【解决方案2】:

像这样扫描溢出:

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。

【讨论】:

    【解决方案3】:

    正如 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");
    }
    

    【讨论】:

      【解决方案4】:

      您将 j 定义为 int。 整数有一个定义的范围。签名整数的最大值为 2,147,483,647。一旦你超过那个值,你就会有一个位溢出,这会导致整个事情从最小值开始。如果是整数,则为 -2,147,483,648。在循环中的某个点,您会得到循环的负起始值,这会导致循环到达 981+19 = 1000 >>> 循环退出,因为 J 等于 for 循环的退出条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-09
        相关资源
        最近更新 更多