简体   繁体   English

整数的Java MAX和MIN值

[英]Java MAX and MIN value for integers

Why is it that (Integer.MAX_VALUE-Integer.MIN_VALUE) = -1 ? 为什么(Integer.MAX_VALUE-Integer.MIN_VALUE) = -1

If you do it on a calculator it becomes a larger positive number but in java it's -1 ? 如果在计算器上执行此操作,它将变成一个更大的正数,但是在Java中,它为-1

This happens because of the arithmetic overflow: MIN_VALUE is a large negative, so subtracting it from MAX_VALUE produces a positive number which is beyond the capacity of an int . 发生这种情况是由于算术溢出: MIN_VALUE是一个很大的负数,因此从MAX_VALUE减去它会产生一个数,该数超出了int的容量。

If you would like to match the results that you get on a calculator, convert int values to long before subtraction: 如果要匹配在计算器上获得的结果,请将int值转换为long然后再减去:

long minInt = Integer.MIN_VALUE;
long maxInt = Integer.MAX_VALUE;
long diff = maxInt - minInt;
System.out.println(diff);

Demo on ideone. ideone上的演示。

Integer overflow. 整数溢出。 If you go outside the bounds of what an Integer can hold it loops back around the other side. 如果超出整数可以容纳的范围,则它会在另一侧循环。

For example try Integer.MAX_VALUE + 1 and see what it gives you. 例如,尝试使用Integer.MAX_VALUE + 1 ,看看它能为您带来什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM