【问题标题】:getting error: incompatible types: possible lossy conversion from double to float for type promotion code出现错误:不兼容的类型:类型提升代码可能从 double 到 float 的有损转换
【发布时间】:2021-09-26 20:44:39
【问题描述】:

执行以下代码时我不明白错误。

public class Main{
    public static void main (String[] args) {
        byte b=2;
        short s=7;
        int i=11002;
        char c = 's';
        float f = 9.987;
        double d = .879;
        int res = (f*b) + (i/c) - (d*s);
        System.out.println("(f*b) + (i/c) - (d*s)");
        System.out.println("result = "+res);
    }
}

我得到的错误:

Main.java:7:错误:不兼容的类型:从双精度到浮点的可能有损转换 浮动 f = 9.987; ^ Main.java:9:错误:不兼容的类型:从 double 到 int 的可能有损转换 int res = (fb) + (i/c) - (ds); ^ 2 个错误

【问题讨论】:

标签: java type-promotion


【解决方案1】:

我猜你是 java 的初学者。所以你犯的错误是 typecasting 。您不能将双精度值分配给浮点类型。

试试这个代码

public class Main{
    public static void main (String[] args) {
        byte b=2;
        short s=7;
        int i=11002;
        char c = 's';
        float f = 9.987f;
        double d = .879;
        int res = (int) ((f*b) + (i/c) - (d*s));
        System.out.println("(f*b) + (i/c) - (d*s)");
        System.out.println("result = "+res);
    }
}

如果您以后不想再遇到这个问题,请了解类型转换(自动转换和显式转换)。

【讨论】:

    【解决方案2】:

    不同数据类型之间的运算结果总是最大的类型(这里是双精度)。 如果您想将结果保留为 int :查看强制转换值。

    应该是这样的:int res = (int) ((f*b) + (i/c) - (d*s))

    否则,使结果为双倍。

    另外,Java 中的浮点数需要以 f 结尾:float f = 9.987f;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多