我编写了一个简单的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
,这是为什么? 最佳答案
要指定数字为浮点数,必须以F或f结尾,这样代码将显示为:
float earthWeight = 195.0f;
float moonWeight = earthWeight * .17f;