【问题标题】:Possible Lossy Conversion error in java from double to intjava中从double到int的可能有损转换错误
【发布时间】:2018-05-17 13:25:22
【问题描述】:

我们已经知道Math.lang()函数在java中的返回类型是double

class Lossy {
    public static void main(String args[]) {
        int sum;
        sum=Math.pow(2,3);
        System.out.println (sum);
    }
}

现在这个语句可能会导致有损转换错误,因为变量是 int 类型,Math.pow() 返回一个double 值,即8.0,这很公平。

现在看看下面的代码有一些变化。

class Lossy {     
    public static void main(String args[]) {
        int sum=2;
        sum+=Math.pow(2,3);
        System.out.println (sum);
    }
}

现在,如果我们编译此代码,我们不会收到可能的转换错误,因为我们在 integer 变量中存储了一个双精度值,所以我们应该得到这个错误。此外,当我们打印该值时,它会显示一个整数值。为什么?

【问题讨论】:

    标签: java operators


    【解决方案1】:

    在第一个代码中,您将一个双精度值分配给一个整数变量。因为双精度值需要 8 个字节,而整数只需要 4 个字节的内存。我们不能将 8 字节的值存储到 4 字节的变量中。这就是为什么它显示可能丢失转换错误。

    class Lossy
      {
       public static void main(String args[])
      {
        int sum;
        sum=Math.pow(2,3);   //Assigning double value to a int variable. its an Error
        System.out.println (sum);
     }
     }
    

    在第二个示例中,您不是简单地或直接地为整数变量赋值。但是您使用了添加和分配运算符(+=),其功能如下:

    sum+=Math.pow(2,3) 等于 sum = sum + Math.pow(2,3);

    当你执行上述操作时,JVM 会为函数 Math.pow() 执行 Automatic Type Conversion(double to int) 或 Parsing 并将函数的返回值转换为 int 而汇编。所以它工作正常。我希望你明白。谢谢!

    【讨论】:

    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多