输入float时出错,输入double时不出错

Error when type float, no error when type 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);
        }
    }

产生输出 "On Earth you weigh 195.0, on the moon you weigh 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,这是为什么?

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

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

这有效

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

参见 javadoc:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Data Type   Default Value (for fields)
float       0.0f

即每个浮点数最后需要一个 "f"

0.17 是 double,因此用 double returns double 运算,在你的例子中这个 earthWeight*.17 returns double 你试着把它保存到 float.

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

这类似于如果你想将 long 保存到 int 中,你不能隐式地这样做,因为它不能完成,如果 long 太大了。 double 和 float 的原理相同。

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

它向您显示错误,因为 java 中的十进制文字隐式为双精度。如果您想将它们用作浮点数,则必须在数字末尾添加字母 F/f。

例如:float earthWeight = 195.0F;