跪求:设计一个Java应用程序,求两点间的距离。要求通过方法重载,能实现求平面和立体两点间的距离
发布网友
发布时间:2022-05-14 15:23
我来回答
共2个回答
热心网友
时间:2023-10-22 09:41
public class Distance {
private Distance.MyPoint p1;
private Distance.MyPoint p2;
public Distance() {
}
public Distance(MyPoint p1, MyPoint p2) {
this.p1 = p1;
this.p2 = p2;
}
public double resultOfdistance() {
return Math.sqrt(
(p1.x - p2.x) * (p1.x - p2.x)
+ (p1.y - p2.y) * (p1.y - p2.y)
+ (p1.z - p2.z) * (p1.z - p2.z));
}
static class MyPoint {
public double x;
public double y;
public double z;
public MyPoint(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public MyPoint(double x, double y) {
this(x, y, 0);
}
}
public static void main(String[] args) {
Distance.MyPoint p1 = new MyPoint(1, 2);
Distance.MyPoint p2 = new MyPoint(3, 4);
Distance d1 = new Distance(p1, p2);
System.out.println("平面两点间距离:" + d1.resultOfdistance());
Distance.MyPoint p3 = new MyPoint(1, 2, 3);
Distance.MyPoint p4 = new MyPoint(4, 5, 6);
Distance d2 = new Distance(p3, p4);
System.out.println("空间两点间距离:" + d2.resultOfdistance());
}
}
热心网友
时间:2023-10-22 09:42
用公式是最简单的,不论平面两点还是空间两点,有坐标就行!代公式马上搞定!方法重载很简单,只是传参不一样…