I wrote the following method in 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. What do I have to do if I need to work with 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
.
public static float surface(float r)
{
return (float)(4*Math.PI*Math.pow(r,2));
}
Please look into Narrowing Primitive Conversion
Math.PI
is defined as 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.
Edit: BTW: consider using BigDecimal
instead of double
or 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.