为什么我可以给 int 的最大值加 1? 该代码的输出是-2147483648。这不是只有在bigValue的类型是long的情况下才可能吗?可能不会?
public class Test {
public static void main (String[] args) {
AddOne addOne = new AddOne();
System.out.println("The value of bigger is " + addOne.plusOne());
}
}
class AddOne {
public long plusOne() {
int value = Integer.MAX_VALUE;
int biggerValue = value + 1;
return biggerValue;
}
}
最佳答案
您应该考虑以位为单位的数字。累积一位并发生溢出。由于整数是有符号的,因此一位流入用作符号的位。
01111111 11111111 11111111 11111111 Base10: Integer.MAX_VALUE
+00000000 00000000 00000000 00000001 Base10: 1
____________________________________
=10000000 00000000 00000000 00000000 Base10: -2147483648
关于java - 为什么我可以给 Integer 的 MAX_VALUE 加 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38504121/