java中可能丢失精度错误
这是我的代码:java中可能丢失精度错误,java,Java,这是我的代码: class test{ public static void main(String arg[]){ int a=10, b=20; float c = 30.123; int e = (int)c; System.out.println(e); } } 我得到了这个错误: test.java:6: error: possible loss of precision float
class test{
public static void main(String arg[]){
int a=10, b=20;
float c = 30.123;
int e = (int)c;
System.out.println(e);
}
}
我得到了这个错误:
test.java:6: error: possible loss of precision
float c = 30.123;
^
required: float
found: double
1 error
为什么所有这些?浮点文本默认为
double
类型。将双精度值指定给浮点类型将导致某些精度错误。您可以将c
的type
更改为double
,或在其末尾附加f
,使其浮动,如下所示:
float c = 30.123f;
如果在末尾指定不带f的浮点值,则默认情况下,它将被视为double
double d = 30.123;
对于float literal,应该在float value的末尾追加f
float c = 30.123f;
@英语:Fouad.)只是想让我的大脑保持忙碌,这样它就不会生锈double作为默认文本类型的原因是double在Java中是非常普通的浮点类型。只有在处理一组非常大的数字时,我才会使用float,但精度有限,处理过程也很好。将c的类型更改为double将是一个更好的解决方案。