gpt4 book ai didi

java - 在方法重载中传递不同数据类型的值

转载 作者:行者123 更新时间:2023-12-03 18:42:06 25 4
gpt4 key购买 nike

我将一个 double 值传递给正在重载的方法,但它将其视为 float 并调用用于查找正方形面积的方法。浮点值应该在其末尾有一个“f”才能被视为浮点,对吗?那么为什么我的程序应该调用“圆的面积”时却调用 float“正方形的面积”呢?

public class App {
public void calArea(float a) {
System.out.println("Area of square is Side x Side : " + a * a);
}

public void calArea(float a, float b) {
System.out.println("Area of rectangle is length x width" + a * b);
}

public void calArea(double r) {
double area = (Math.PI * r * r);
System.out.println("Area of circle is Radius x Radius x PI : " + area);
}

public static void main(String[] args) {

App app = new App();

app.calArea(5);
}

}

最佳答案

我只是将我的评论作为答案发布,因为这是无需强制转换即可解决您的问题的唯一方法。

而不是使用doublefloat来区分应该计算哪些面积。只是以不同的方式命名它们。这将消除您在查看代码时的很多头痛。

Will app.calArea(5) calculate the area of a circle or a square?

所以只需将代码更改为:

public class App {
public void calAreaSquare(double a) {
System.out.println("Area of square is Side x Side : " + a * a);
}

public void calAreaRectangle(double a, double b) {
System.out.println("Area of rectangle is length x width" + a * b);
}

public void calAreaCircle(double r) {
double area = (Math.PI * r * r);
System.out.println("Area of circle is Radius x Radius x PI : " + area);
}

public static void main(String[] args) {

App app = new App();

app.calAreaCircle(5);
}
}

我还建议仅使用double,以提高精度。

关于java - 在方法重载中传递不同数据类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51150051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com