java - 为什么这不能正确检测整数溢出?
问题描述
为什么这不能正确检测整数溢出?
private static float calc(float a, int b){
float sum = a;
for (int i = 1; i <= b; i++){
assert Math.abs(a) <= Integer.MAX_VALUE : "Overflow";
sum = sum * sum;
}
return sum;
}
解决方案
该assert
语句使用永远不会改变的变量a
。它应该使用sum
.
默认情况下,断言在运行时被禁用,因此您需要java
使用-enableassertions
(or -ea
) 开关运行。
示例用法:
class TestOverflow<T> {
public static void main(String[] args) {
System.out.println(calc(2.0f, 6));
}
private static float calc(float a, int b){
float sum = a;
for (int i = 1; i <= b; i++){
assert Math.abs(sum) <= Integer.MAX_VALUE : "Overflow";
sum = sum * sum;
}
return sum;
}
}
编译并运行:
$ java -ea -cp out/production/scratchpad/ TestOverflow
Exception in thread "main" java.lang.AssertionError: Overflow
at TestOverflow.calc(TestOverflow.java:12)
at TestOverflow.main(TestOverflow.java:4)
推荐阅读
- javascript - 如何在没有 webpack 的其他加载器的情况下使用样式加载器?
- python - 什么导致 TensorFlow 导入错误:DLL 加载失败?
- neo4j - Neo4J 升级:为什么用户角色没有转移?
- android - 如何设置 TabLayout 的 ta 的圆形波纹形状?
- php - 带有白色字段的html表单到mysql
- java - 在 Android 上执行 MediaRecoder.start() 时出现 IllegalStateException
- c - 在输入 N 之后创建结构的 N 个元素
- css - 垂直滚动线
- flutter - FutureBuilder 类参数 future 是一个带参数的异步函数
- c# - 有没有聪明的方法让这个填充更少?如果是怎么办?