教我如何在Java中重载方法的练习程序会输出错误的答案

时间:2014-01-19 01:26:51

标签: java methods

我理解重载的概念,我想我已经在这个程序中成功完成了它;它运行正常,但输出不正确。

该程序应该从两个点计算圆的面积,一个是半径,另一个是圆外侧的随机点。这两点由用户给出,每个点由两个数字组成。因此,第一点是x1,x2,而第二点是y1,y2。

我通过输入数字1,2,3和4进行了测试运行,这应该给出3.1458 ....(pi)的答案。但是,它给了我25.132741228718352。

任何有关弄清楚是什么给我这个奇怪输出的帮助都会非常感激。

以下是代码 import java.util.Scanner; 公共类AreaCircle {

static Scanner input  = new Scanner(System.in);

public static double getDistance(double x1, double y1,
                            double x2, double y2) {

    double dx = x2 - x1;
    double dy = y2 - y1;

    double distanceSquared = dx * dx + dy * dy;
    double radius = Math.sqrt(distanceSquared);
    return radius;
}

public static double areaCircle (double radius){
double area = (double)Math.PI * (radius * radius);
return area;
}

public static double areaCircle (double x1, double x2,
                                    double y1, double y2) {
    double radius = getDistance(x1, x2, y1, y2);

    double area = areaCircle (radius);

    return area;

}
public static void main(String[] args) {
System.out.print("Please input two points, with the first being \n"
        + "the middle of the circle and the other being \n"
        + "a point on the outside of the circle. These two points will \n"
        + "be used to find the area of your circle. \n\n"
        + "Input the first point here: ");
double x1 = input.nextDouble();
System.out.print("Input the second point here: ");
double x2 = input.nextDouble();
System.out.print("Input the third point here: ");
double y1 = input.nextDouble();
System.out.print("Input the fourth point here: ");
double y2 = input.nextDouble();
double result = areaCircle(x1, x2, y1, y2);
System.out.println("Your result is: " + result);
}

}

1 个答案:

答案 0 :(得分:0)

您实际上是在计算(1,2)和(3,4)之间的距离,因为您已在x2中使用y1切换distance(将其与area功能 - 你会看到我的意思。)

(1,2)和(3,4)之间的距离是sqrt 8,当你将其替换为公式时,它给出的面积为8 * pi~ = 25.