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

Sheeraz Gul 2023年10月12日

在 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
``````

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.