【问题标题】:Unexpected output for int typeint 类型的意外输出
【发布时间】:2014-08-21 12:55:28
【问题描述】:

学习 JAVA,我试图测试 while 循环的上限,该循环不断增加 int。请参阅下面的程序:

 public class Test {

   public static int a(){
     int a = 10;
      while(a > 9 )
          ++a;
      return a; 
   }

   public static void main(String[] argc) {

         Test t = new Test();
         int k = t.a();
         System.out.println("k = "+(1 * k));    
    }
}

我知道 32 位的范围是从 -2,147,483,648 到 2,147,483,647,因此在此基础上,我期望输出为 2,147,483,647,但我得到的是:

k = -2147483648

我什至尝试过

 System.out.println("k = "+(1 * k/2)); 

但输出仍然是:

k = -1073741824

问题:

为什么解应该是正的却是负的?

【问题讨论】:

    标签: java int size


    【解决方案1】:

    您将a int 增加1 直到达到1 + Integer.MAX_VALUE,这会将其值转移到-2147483648 == Integer.MIN_VALUE

    这是你的循环评论:

    // "infinite" loop as a is assigned value 10
    while(a > 9)
        // when a reaches Integer.MAX_VALUE, it is still incremented by 1
        ++a;
    // loop condition now false, as value for a has shifted to -2147483648
    return a; 
    

    【讨论】:

    • 问题:所以当我们越过Integer.MAX_VALUE时,我们会自动转移到Integer.MIN_VALUE...反过来也是如此吗?
    • @NoobEditor 是的。 Integer.MIN_VALUE - 1 == Integer.MAX_VALUE 因为没有明确的上溢或下溢错误。
    • 我希望我在 2 年前就知道这一点!我很困惑。感谢您的明确回答,+1
    【解决方案2】:

    正在发生的事情称为integer overflow

    二进制的最大 32 位整数值为:

    0111 1111 1111 1111 1111 1111 1111 1111

    当你给这个数字加 1 时,你会得到:

    1000 0000 0000 0000 0000 0000 0000 0000

    这是twos compliment,或-2,147,483,648。由于任何负数都小于 9,因此退出 while 循环。

    【讨论】:

      【解决方案3】:

      你增加值直到它达到正限制,它变成所有位,但符号位变成 1。

      0x7FFFFFFF = 01111111 11111111 11111111 11111111

      这是 2147483647 的二进制表示,即 INT_MAX。当你再次将它加一时,它变成了

      0x80000000 = 10000000 00000000 00000000 00000000

      等于 INT_MIN,-2147483648。

      现在,

      2147483647 大于 9,因此您的循环继续。再增加一个,哎呀,突然它是 -2147483648,它小于 9。这就是你的循环条件失败的地方。

      【讨论】:

        【解决方案4】:

        如果我们查看Oracle docs on int values,我们可以发现:

        The operators that work on the int primitive value do not indicate overflow or underflow

        结果由JVM版本的语言独立指定如下:

        Integer.MAX_VALUE + 1 is the same as Integer.MIN_VALUE
        Integer.MIN_VALUE - 1 is the same as @ 987654328@

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-19
          相关资源
          最近更新 更多