错误:不兼容的类型:从double到float的可能有损转换

huangapple go评论91阅读模式
英文:

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

问题

我一直在运行这段代码,但不断收到错误消息,不太清楚原因。从双精度到单精度?一直收到“错误:不兼容的类型:从双精度到单精度的可能丢失转换”消息。在转换方面是否有任何问题,如何进行转换以避免错误。这是较大代码的一部分。

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

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;
}

答案1

得分: 0

你需要进行类型转换。或者将 area 声明为 double

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

或者

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

另外:你在同一个方程中混合使用了整数和浮点数。通常这会导致问题。最好使用双精度浮点数字面值。

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

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;

huangapple
  • 本文由 发表于 2020年9月28日 11:31:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64095591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定