HOWTO · Java

在 Java 中计算两点之间的距离

本教程演示如何在 Java 中计算两点之间的距离。

本页内容

使用勾股定理,我们可以在 Java 中找到两点之间的距离。本教程演示如何在 Java 中计算两点之间的距离。

在 Java 中计算两点之间的距离

例如,X 和 Y 两点坐标 (x1, y1) 和 (x2, y2),这两点之间的距离可以表示为 XY,勾股定理可以用 Java 实现来计算距离。

下图中的方程代表了这两个点的勾股定理。

勾股定理

让我们尝试在 Java 中实现勾股定理。

package delftstack;

import java.util.Scanner;
public class Distance_Two_Points {
  public static void main(String[] args) {
    Scanner Temp = new Scanner(System.in);

    // declare the variables
    int x1;
    int x2;
    int y1;
    int y2;
    int x;
    int y;
    double Distance_Result;

    // get the input coordinates
    System.out.print("Enter the values of first point coordinates : ");
    x1 = Temp.nextInt();
    y1 = Temp.nextInt();
    System.out.print("Enter the values of second point coordinates : ");
    x2 = Temp.nextInt();
    y2 = Temp.nextInt();

    // Implement pythagorean theorem
    x = x2 - x1;
    y = y2 - y1;
    Distance_Result = Math.sqrt(x * x + y * y);

    System.out.println("Distance between the two points is : " + Distance_Result);
  }
}

上面的代码将取两点的坐标,然后通过勾股定理计算距离。见输出:

Enter the values of first point coordinates : 12
21
Enter the values of second point coordinates : 13
34
Distance between the two points is : 13.038404810405298