Java

怎么用java求任意两点之间的距离

小亿
177
2023-11-14 22:47:43
栏目: 编程语言

要使用Java求任意两点之间的距离,可以使用以下步骤:

  1. 创建一个名为Point的类,该类表示一个点。该类应该包含xy两个属性,并提供相应的getter和setter方法。
public class Point {
    private double x;
    private double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }
}
  1. 创建一个名为DistanceCalculator的类,该类包含一个静态方法calculateDistance,用于计算两点之间的距离。该方法接受两个Point对象作为参数,并返回一个double类型的距离值。
public class DistanceCalculator {
    public static double calculateDistance(Point point1, Point point2) {
        double xDiff = point2.getX() - point1.getX();
        double yDiff = point2.getY() - point1.getY();
        return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
    }
}
  1. 在主程序中,创建两个Point对象,然后调用DistanceCalculator的静态方法来计算它们之间的距离。
public class Main {
    public static void main(String[] args) {
        Point point1 = new Point(1, 2);
        Point point2 = new Point(3, 4);

        double distance = DistanceCalculator.calculateDistance(point1, point2);
        System.out.println("Distance between point1 and point2: " + distance);
    }
}

上述代码将输出"Distance between point1 and point2: 2.8284271247461903",表示两点之间的距离为2.8284271247461903。

0
看了该问题的人还看了