用Java计算一个point类计算两个点之间的距离
时间: 2024-12-13 12:21:34 浏览: 22
在Java中,你可以创建一个Point类来表示二维空间中的点,并包含x和y坐标。然后定义一个静态方法`distance(Point p1, Point p2)`来计算两点之间的欧氏距离。以下是简单的示例:
```java
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// Getters and setters for x and y coordinates (省略)
// 计算两点之间的欧氏距离
public static double distance(Point p1, Point p2) {
double dx = p1.getX() - p2.getX();
double dy = p1.getY() - p2.getY();
return Math.sqrt(dx * dx + dy * dy);
}
}
// 使用方法示例
public class Main {
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
double dist = Point.distance(p1, p2);
System.out.println("Distance between points is: " + dist);
}
}
```
阅读全文