[英]JAVA : possible loss of precision
I wrote the following method in JAVA : 我在JAVA中编写了以下方法:
public static float surface(float r)
{
return(4*Math.PI*Math.pow(r,2));
}
when I run the class, I got the following error : 当我运行该类时,我收到以下错误:
possible loss of precision
required: float; found: double
I saw in the doc that Math.pow needs double
to work. 我在文档中看到Math.pow需要
double
才能工作。 What do I have to do if I need to work with float
? 如果我需要使用
float
我该怎么办?
To test, I tried to following method, which is giving the same error : 为了测试,我尝试了以下方法,它给出了同样的错误:
public static float surface(float r)
{
return(4*Math.PI*r*r);
}
Thank you for your help. 谢谢您的帮助。
you need to type cast double
to float
. 你需要输入cast
double
来float
。
public static float surface(float r)
{
return (float)(4*Math.PI*Math.pow(r,2));
}
Please look into Narrowing Primitive Conversion 请看一下Narrowing Primitive Conversion
Math.PI
is defined as double
. Math.PI
被定义为double
。 Since you're returning a float
, there has to be a conversion from double
to float
"anywhere" - which is a possible loss of precision. 因为你要返回一个
float
,所以必须在“任何地方”从double
转换为float
- 这可能会导致精度损失。
Edit: BTW: consider using BigDecimal
instead of double
or float
. 编辑:BTW:考虑使用
BigDecimal
而不是double
或float
。 If you use "BigDecimal" and "float" as keywords for a search in the web, you'll find many articles dealing with this topic explaining the advantages and disadvantages of each approach. 如果您使用“BigDecimal”和“float”作为网络搜索的关键字,您会发现许多涉及此主题的文章解释了每种方法的优缺点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.