首页 > 解决方案 > 对我的 int 和 long 代码差异的问题

问题描述

嘿嘿,当我学习新的基础知识时,我发现 int 的限制为 2^32 -1 所以我想知道我是否可以用 unsigned int 或 long 来增加它

我尝试了以下

class test {
    public static void main(String[] args) {
        int i;
        int a=0;

        for (i=1; i>0; i++) {
            a++;
        }
        System.out.println("Done, a=" +a);
    }
}

我注意到改变 long a=0 不会改变输出,但为什么呢?

将 i 更改为 long 确实会更改输出

在我的理解中 i 的值仍然为 0 那么它为什么会达到极限呢?

有没有办法改进我找到极限的方法?

标签: javaint

解决方案


如果a是我们的 long,我们的程序将在达到 a 的 MAXVALUE 之前停止 for 循环long所以 的值为a2147483647。

class Test {
  public static void main(String[] args) {
    int i;
    long a = 0;

    for(i = 1; i > 0; i++) {
      // This will stop incrementing when we reach the MAXVALUE
      // of an int (i), which is 2147483647
    }

    System.out.println(a);
  }
}

如果是我们的 long,我们的程序将在达到(整数)的 MAXVALUEi尝试循环(递增) -所以我们的程序将挂起并且不会打印任何内容。a

class Test {
  public static void main(String[] args) {
    long i;
    int a = 0;

    for(i = 1; i > 0; i++) {
      // This will try to increment **a** beyond the max
      // value of an int
    }

    System.out.println(a);
  }
}

推荐阅读