int溢出判断
// int存储最小值:-2147483648
Integer.MIN_VALUE = 0x80000000;
// int存储最大值:2147483648
Integer.MAX_VALUE = 0x7fffffff;
先做一个简单的加减测试
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
System.out.println("Integer.MAX_VALUE:" + max); System.out.println("Integer.MIN_VALUE:" + min);
System.out.println("max + 1 = " + (max + 1));
System.out.println("min - 1 = " + (min - 1));
Integer.MAX_VALUE:2147483647
Integer.MIN_VALUE:-2147483648
max + 1 = -2147483648
min - 1 = 2147483647
可以发现:最大值加1变成最小值,最小值减1变为最大值,如此循环
那么可以猜想单用int本身来判断是否溢出是行不通或者不严谨的
行不通:直接判断是没有好结果的
if (max + 1 > Integer.MAX_VALUE)
System.out.println("正向溢出");
else
System.out.println("???");
if (min - 1 < Integer.MIN_VALUE)
System.out.println("负向溢出");
else
System.out.println("???");
???
???
不严谨:如果一个正数溢出就变负数,负数溢出就变正数?
但是:一个正数,万一我加了两个max再加2不就又转回去变成正数了。。。
if (max + 1 < 0)
System.out.println("正向溢出");
else
System.out.println("???");
if (min - 1 > 0)
System.out.println("负向溢出");
else
System.out.println("???");
if (max + max + 2 < 0)
System.out.println("正向溢出");
else {
System.out.println("??? max + max + 2 = " + (max + max + 2));
}
正向溢出
负向溢出
??? max + max + 2 = 0
因此,想要真正实现与Integer.MAX_VALUE,Integer.MIN_VALUE比较大小,那么那个数一定可以比Integer.MAX_VALUE大,比Integer.MIN_VALUE小,int类型是无法存储这些数的,因此要用long,float,double来比较。
if ((long) max + 1 > (long) max)
System.out.println("正向溢出 (long)max + 1 = " + ((long) max + 1));
if ((long) min - 1 < (long) min)
System.out.println("负向溢出 (long)min - 1 = " + ((long) min - 1));
正向溢出 (long)max + 1 = 2147483648
负向溢出 (long)min - 1 = -2147483649
附上所有代码和结果
public class IntTest {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
System.out.println("Integer.MAX_VALUE:" + max);
System.out.println("Integer.MIN_VALUE:" + min);
System.out.println("max + 1 = " + (max + 1));
System.out.println("min - 1 = " + (min - 1));
if (max + 1 > Integer.MAX_VALUE)
System.out.println("正向溢出");
else
System.out.println("???");
if (min - 1 < Integer.MIN_VALUE)
System.out.println("负向溢出");
else
System.out.println("???");
if (max + 1 < 0)
System.out.println("正向溢出");
else
System.out.println("???");
if (min - 1 > 0)
System.out.println("负向溢出");
else
System.out.println("???");
if (max + max + 2 < 0)
System.out.println("正向溢出");
else {
System.out.println("??? max + max + 2 = " + (max + max + 2));
}
if ((long) max + 1 > (long) max)
System.out.println("正向溢出 (long)max + 1 = " + ((long) max + 1));
if ((long) min - 1 < (long) min)
System.out.println("负向溢出 (long)min - 1 = " + ((long) min - 1));
}
}
Integer.MAX_VALUE:2147483647
Integer.MIN_VALUE:-2147483648
max + 1 = -2147483648
min - 1 = 2147483647
???
???
正向溢出
负向溢出
??? max + max + 2 = 0
正向溢出 (long)max + 1 = 2147483648
负向溢出 (long)min - 1 = -2147483649
2040

被折叠的 条评论
为什么被折叠?



