代码之家  ›  专栏  ›  技术社区  ›  impossible

双整数值溢出

  •  3
  • impossible  · 技术社区  · 7 年前

    public static void main(String[] args) {
    
        System.out.println(getSomeValue());
        System.out.println(getFixedSomeValue());
    }
    
    private static double getSomeValue() {
        return (2500000 - 0) * 250000 * (200 + 310);
    }
    
    private static double getFixedSomeValue() {
        return (double) (2500000 - 0) * 250000 * (200 + 310);
    }
    

    输出:

    -9.9787264E8
    3.1875E14
    

    Double.MAX_VALUE = 1.7976931348623157E308
    Integer.MAX_VALUE = 2147483647
    

    当方法的返回类型为double时,是否应自动将其强制转换为double?

    3 回复  |  直到 7 年前
        1
  •  8
  •   Michael    7 年前

    (2500000 - 0) * 250000 * (200 + 310) 是一个由 int 文本和数字运算符,因此使用整数运算符对其进行计算,结果是 Integer.MAX_VALUE double 在方法返回之前,但为时已晚。

    (double) (2500000 - 0) 值。这和写作相似

    return (2500000.0 - 0) * 250000 * (200 + 310)
                   ^ decimal point = double literal rather than int
    
        2
  •  0
  •   Ankit Kathait    7 年前

        3
  •  0
  •   Andy Turner    7 年前

    当方法的返回类型为double时,是否应自动将其强制转换为double?

    是的,也许不是你的意思。

    private static double getSomeValue() {
        return (2500000 - 0) * 250000 * (200 + 310);
    }
    

    private static double getSomeValue() {
        int e = (2500000 - 0) * 250000 * (200 + 310);
        return (double) e;
    }
    

    int double