【发布时间】:2014-02-08 12:06:30
【问题描述】:
如果我没记错的话,“0.5”是十进制数;因此,使其成为浮点值。但为什么 java 告诉我它是双精度的?返回语句被 java 检测为错误,说:“不兼容的类型:从双精度到浮点的可能有损转换”
public float typeDmgMultiplr(String type,String type2){
if(type.equalsIgnoreCase("grass")){
if(type2.equalsIgnoreCase("grass"))
return 0.5;
else if(type2.equalsIgnoreCase("poison"))
return 0.5;
else if(type2.equalsIgnoreCase("fire"))
return 0.5;
else
return 2.0;
}
else if(type.equalsIgnoreCase("fire")){
if(type2.equalsIgnoreCase("grass"))
return 2.0;
else if(type2.equalsIgnoreCase("poison"))
return 1.0;
else if(type2.equalsIgnoreCase("fire"))
return 0.5;
else
return 0.5;
}
else if(type.equalsIgnoreCase("water")){
if(type2.equalsIgnoreCase("grass"))
return 0.5;
else if(type2.equalsIgnoreCase("poison"))
return 1.0;
else if(type2.equalsIgnoreCase("fire"))
return 2.0;
else
return 0.5;
}
else{
if(type2.equalsIgnoreCase("grass"))
return 2.0;
else if(type2.equalsIgnoreCase("poison"))
return 0.5;
else if(type2.equalsIgnoreCase("fire"))
return 1.0;
else
return 1.0;
}
}
【问题讨论】:
-
0.5默认为double类型。附加f使其成为float-0.5f -
double是 double 精度的浮点数,float是 single 精度的浮点数。如果您只写0.5,那么它会被解释为double。要使用float类型,您必须将其写为0.5f。 -
除非你有充分的理由,否则不要使用
float。大多数时候这只是一个不必要的头痛。 -
当你迁移到 Java-8 时,你会更加头疼,发现很多很酷的新特性根本不支持
float类型。
标签: java