键入float时出错,键入double时没有错误

时间:2015-03-10 20:50:43

标签: java floating-point double

我写了一个简单的java程序,输出你在月球上的重量。以下代码

    class MoonWeight
    {
        public static void main(String args[])
        {
            double earthWeight = 195.0;
            double moonWeight = earthWeight*.17;
            System.out.println("On Earth you weigh " + earthWeight +
            ", on the moon you weigh " + moonWeight);
        }
    }

产生输出“地球上你重195.0,月亮你重33.150000000000006”,但当我使用类型float时:

    class MoonWeight
    {
        public static void main(String args[])
        {
            float earthWeight = 195.0;
            float moonWeight = earthWeight*.17;
            System.out.println("On Earth you weigh " + earthWeight +
            ", on the moon you weigh " + moonWeight);
        }
    }

我收到以下错误error: incompatible types: possible lossy conversion from double to float,为什么会这样?

5 个答案:

答案 0 :(得分:4)

要指定数字是浮点数必须以F或f结尾,因此代码将显示为:

float earthWeight = 195.0f;
float moonWeight = earthWeight * .17f;

答案 1 :(得分:1)

这是有效的

    float earthWeight = 195.0f;
    float moonWeight = earthWeight*0.17f;

请参阅javadocs:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Data Type   Default Value (for fields)
float       0.0f

即。每个浮点数最后都需要一个“f”

答案 2 :(得分:1)

0.17是double,因此使用double返回的操作为double,在您的示例中,此earthWeight*.17返回double并尝试将其保存为float。

要修复它,你必须使用float,这非常简单:earthWeight*.17f

就像你想长期保存到int一样,如果那么长就太大,你就无法完全无法做到这一点。同样的原则是double和float。

答案 3 :(得分:0)

这是因为浮点精确度不如双精度。如果将数字从double转换为float,则可能会丢失信息。编译器会告诉您这个问题。

答案 4 :(得分:0)

它显示错误,因为java中的十进制文字隐式地加倍。如果你想把它们用作浮动,你必须在你的号码末尾加上字母F / f。

例如:float earthWeight = 195.0F;