英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论