我是编程方面的新手。我正在学习一本Java对象编程书,并在计算机上同时执行该书中的教程和示例。书中说整数的最大值和最小值是;
Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648
Run Code Online (Sandbox Code Playgroud)
那么好吧。这里没有问题,但是;它表示如果我们将最大值加1并从最小值减去1;
class test {
public static void main(String[] args) {
int min = Integer.MIN_VALUE -1;
int max = Integer.MAX_VALUE +1;
int a = min - 1;
int b = max + 1;
System.out.println("min - 1 =" + a);
System.out.println("max - 1 =" + b);
}
}
Run Code Online (Sandbox Code Playgroud)
因此我们发现
min - 1 = 2147483646
max + 1 = -2147483647
Run Code Online (Sandbox Code Playgroud)
它说此结果是因为内存中的二进制进程限制为32位。我无法理解的事情。在代码段中,它不是分别从最大值和最小值分别减去2吗?
int min = Integer.MIN_VALUE -1; // subtracted 1 here
int max = Integer.MAX_VALUE +1; // added 1 here
int a = min - 1; // subtracted 1 here
int b = max + 1; // added 1 here
Run Code Online (Sandbox Code Playgroud)
请注意,a是Integer.MAX_VALUE - 1和b是Integer.MIN_VALUE + 1。所以是的,在每种情况下,它的确减去两次。这本书没错,但是这是一种关于环绕溢出的愚蠢教学方式。只是印刷Integer.MIN_VALUE - 1和Integer.MAX_VALUE + 1会提出的观点。
int min = Integer.MIN_VALUE -1; // min is set to Integer.MAX_VALUE by underflow
int max = Integer.MAX_VALUE +1; // max is set to Integer.MIN_VALUE by overflow
Run Code Online (Sandbox Code Playgroud)
如果整数加法溢出,则结果是数学和的低阶位,以某种足够大的二进制补码格式表示。
JLS是解决此类问题的最终权威,但我不建议您将其作为学习Java的一种方式。最好阅读Java语言教程。它相当全面,内容质量很高。