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