Search code examples
javadoubleequationarea

Error: incompatible types: possible lossy conversion from double to float


I've been running this code and keep receiving errors, not sure why. Double to float? Keep receiving message "error: incompatible types: possible lossy conversion from double to float ." Is there any issue with conversions how to the conversion so there is no error This is part of a larger code.

  public static float getAreaOfPentagon(float l) {
  float area = Math.sqrt(5 * (5 + 2 * (Math.sqrt(5))) * l * l) / 4;
  return area;
}

Solution

  • You need to cast. Or declare area as double.

    float area = (float)(Math.sqrt(5 * (5 + 2 *
       (Math.sqrt(5))) * l * l) / 4);
    

    or

    double area = Math.sqrt(5 * (5 + 2 *
       (Math.sqrt(5))) * l * l) / 4;
    

    Aside: you are mixing integers and floating point in the same equation. Often this leads to disaster. It's probably better to use double literals.

    double area = Math.sqrt(5.0 * (5.0 + 2.0 *
       (Math.sqrt(5.0))) * l * l) / 4.0;