首页 > 解决方案 > 通过使用多种方法,找到具有给定坐标的三角形的周长

问题描述

import java.util.Scanner;
public class Perimeter {


public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter X1: ");
    double X1 = scan.nextDouble();
    System.out.println("Please enter Y1: ");
    double Y1 = scan.nextDouble();
    System.out.println("Please enter X2: ");
    double X2 = scan.nextDouble();
    System.out.println("Please enter Y2: ");
    double Y2 = scan.nextDouble();
    System.out.println("Please enter X3: ");
    double X3 = scan.nextDouble();
    System.out.println("Please enter Y3: ");
    double Y3 = scan.nextDouble();

    finddistance(X1,Y1,X2,Y2,X3,Y3);
    double answer = triperimeter(base1, base2, base3);
    System.out.println(answer);

}

public static finddistance(double X1, double Y1, double X2, double Y2, double X3, double Y3){
    double base1 = Math.sqrt(Math.pow((X2 - X1),2) + Math.pow((Y2 - Y1),2));
    double base2 = Math.sqrt(Math.pow((X3 - X1),2) + Math.pow((Y3 - Y1),2));
    double base3 = Math.sqrt(Math.pow((X3 - X2),2) + Math.pow((Y3 - Y2),2));
}

public static double triperimeter(double base1, double base2, double base3){
    return (double) base1 + base2 + base3;
}
}

我们现在正在学习如何使用多种方法编写代码,我认为我的错误如下:

在方法 finddistance 中,我需要以某种方式与此代码中的所有方法共享/返回变量 base123,但我不知道该怎么做。

当我编译这段代码时,它只会给我一个错误消息:无效的方法声明,需要返回类型。在公共静态 finddistance 线上。

标签: javamathjava.util.scanner

解决方案


我怀疑你的老师想要的是有一种findDistance方法,只计算一个距离,但你调用了 3 次。然后,当您计算出三个长度时,如果您愿意,可以将它们全部添加到单独的方法中。

另请注意,通常更准确地使用Math.hypot代替Math.sqrtandMath.pow一起使用。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter Ax: ");
    double ax = scan.nextDouble();
    System.out.println("Please enter Ay: ");
    double ay = scan.nextDouble();
    System.out.println("Please enter Bx: ");
    double bx = scan.nextDouble();
    System.out.println("Please enter By: ");
    double by = scan.nextDouble();
    System.out.println("Please enter Cx: ");
    double cx = scan.nextDouble();
    System.out.println("Please enter Cy: ");
    double cy = scan.nextDouble();

    double lengthA = findDistance(bx, by, cx, cy);
    double lengthB = findDistance(ax, ay, cx, cy);
    double lengthC = findDistance(ax, ay, bx, by);

    double answer = perimeter(lengthA, lengthB, lengthC);
    System.out.println(answer);

}

public static double findDistance(double x1, double y1, double x2, double y2){
    return Math.hypot( x2 - x1, y2 - y1 ); 
}

public static double perimeter(double length1, double length2, double length3) {
    return length1 + length2 + length3;
}

推荐阅读