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

Sheeraz Gul 2022年5月31日
在 Java 中计算两点之间的距离

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

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

例如,XY 两点坐标 (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
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java Math