0

For some reason I am getting a precision error when I try to compile my code. The precision error comes in the return of my second method where I am trying to calculate the circumference. What am I doing incorrectly?

public class Methods2
{
   public static final double PI = 3.14;
   public static double calcCirc(double x)
   {
      return PI*x;
   }
   public static int calcCirc(int x)
   {
      return (2*(double) x)*PI;
   }
   public static void main(String[]args)
   {
      System.out.println(calcCirc(10.2));
      System.out.println(calcCirc(4));
   }
}
4

3 回答 3

3

You are attempting to return a double value in a method declared to return an int. Java won't let you implicitly narrow your value like that.

If you're okay with the loss of precision, then explicitly cast the value to int -- Java will let you do that.

return (int) ((2*(double) x)*PI);

However, I would change the method to return double instead, not to lose precision:

public static double calcCirc(int x)

... as you already did with your other calcCirc method.

于 2013-09-27T23:43:35.190 回答
2

Both versions of calcCirc() ought to return doubles.

Also, side note--consider using different method names since they accept inputs that differ not only in type but also in semantics.

E.g. calcCircFromRadius(double radius), calcCircFromDiameter(double diameter). There's not really a reason to take an int as an input type here since Java will automatically cast ints to doubles for you.

于 2013-09-27T23:43:07.933 回答
0

尝试

public static int calcCirc(int x){
    return (int)((2*x)*PI);
}
于 2013-09-27T23:46:24.060 回答