You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Math.pow(2,31)强制转换为int未按预期发生溢出环绕的问题咨询

Math.pow(2,31)强制转换为int未按预期发生溢出环绕的问题咨询

大家好,我最近在验证数值超出容器可容纳范围时的溢出环绕特性,针对int类型的边界值做了测试,但结果和预想的不一样,想请教下各位问题出在哪。

我写的测试代码如下:

public class Main {
    public static void main(String[] args) {
        double value = Math.pow(2,31);
        System.out.println("Raw double: " + value);
        System.out.println("After casting to int: " + (int)value);
        System.out.println("Integer.MAX_VALUE: " + Integer.MAX_VALUE);
    }
}

我在JShell(版本20.0.2,java 20.0.2 2023-07-18)和Programiz在线编译器上都运行了这段代码。

我预期的输出是:

Raw double: 2.147483648E9
After casting to int: -2147483648
Integer.MAX_VALUE: 2147483647

但实际得到的输出却是:

Raw double: 2.147483648E9
After casting to int: 2147483647
Integer.MAX_VALUE: 2147483647

后来我考虑到Math.pow()返回的是double类型,可能存在精度损失的问题,于是改用了移位运算符1L<<31来生成数值,但转换后的结果还是和上面一样,没有得到预期的溢出值。

有没有大佬能帮我解释下为什么会出现这种情况?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:44:38