【问题标题】:Java for loop is negativeJava for 循环是否定的
【发布时间】:2020-02-24 01:22:27
【问题描述】:

当你运行下面的代码时

  1. count 值变为 -1,程序以除以零异常结束。

  2. 当您取消注释 sysout 时,它运行良好。不确定sysout 有何不同。

public class HelloWorld{
    public static void main(String []args){

         int num = 1;
         int count;
         int sum;
         int fact;
         for(count=1,sum=0,fact=1;fact<=num;count=count+1){

            //System.out.println("num:"+num+" fact:"+fact+" count:"+count+" sum:"+sum);

             if(num%count==0){

                fact = num/count;
                sum  = sum+fact;
                System.out.println("num:"+num+" fact:"+fact+" count:"+count+" sum:"+sum);
             }

         }
    }
}

输出:

num:1 事实:1 count:1 sum:1

num:1 事实:-1 计数:-1 sum:0

线程“主”java.lang.ArithmeticException 中的异常:/ 为零 在 HelloWorld.main(HelloWorld.java:14)

【问题讨论】:

  • 你确定你显示的代码生成了这个输出吗?如果是这样,您可以启用第一个打印语句并重新生成输出吗?
  • 我很确定这里发生的事情是你循环遍历所有 int 值。 1%1 为真,但 1%n 的所有其他值均为假。那是为了积极的价值观。一旦你溢出 int,我不相信 1%0 是零,所以你不要尝试打印。但是,我猜 1%-1 为零。 (我有一段时间没看过模数的正式定义,但我认为它是这样的。)底线是“如果”语句在零上不正确。然而,这并不能解释为什么 system.out.println() 会改变结果。

标签: java loops for-loop negative-number


【解决方案1】:

你不断增加计数,它最终溢出并环绕到0

In binary, Integer.MAX_VALUE = 2147483647 = 01111111 11111111 11111111 11111111                                              
                                            ^
                                            sign bit (positive)

When you add one more to the number it becomes

          Integer.MIN_VALUE = -2147483648 = 1000000 000000 000000 000000 000000
                                            ^
                                            sign bit (negative)

所以它会环绕并从 Integer.MAX_VALUE 变为 Integer.MIN_VALUE。

  for(int count=Integer.MAX_VALUE -10; count != Integer.MIN_VALUE + 10; count++){
         System.out.println("count = " + count);
  }

如您所见,如果您继续将1 添加到count,它最终会增加到0,并且您会得到除以0 的错误。

您可以在 Wikipedia 上阅读有关 Two's Complement Representation 的更多信息。

【讨论】:

    【解决方案2】:

    当计数值大于 Integer.MAX_VALUE 时,计数被定义为整数 它溢出并变为负数。

    由于 (1 % 任何大于 1 的数字) 不能为零,因此循环继续进行,计数值不断增长,并在 Integer.MAX_VALUE 循环后溢出。

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 2013-06-28
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      相关资源
      最近更新 更多