为什么我不能用一个浮点和一个布尔变量将加仑转换为 letre



//将加仑转换为 leter

class galtolit
{
    public static void main(String[] args)
    {
      double liter;// if this variable is float it throws incompatible type error 
                  // why i can't take float?              
      double gallons =10;
      liter= gallons * 3.7854;
      System.out.println(gallons + "  gallons = "+ liter+"  liter");
    }   
}

如果此变量是浮点数,则会抛出不兼容的类型错误 为什么我不能乘坐浮动?

因为如果没有显式转换,您不能获取double值并将其降级为float,因为在此过程中会失去精度。请记住:float是 32 位 IEEE-754 精度浮点值; double 是一个 64 it 的 IEEE-754 精度浮点值。(更多内容见JLS)

这里没有理由使用float。坚持使用double,这为您提供更高的精度。

要将双精度转换为浮点数,您必须为类型转换添加"f"。见下文:

class galtolit {
    public static void main(String[] args) {
        float liter;// if this variable is float it throws incompatible type
                    // error
        // why i can't take float?
        float gallons = 10;
        liter = gallons * 3.7854f;
        System.out.println(gallons + "  gallons = " + liter + "  liter");
    }
}

最新更新