我想要获得坐标之间的距离,并且由于某种原因它似乎不起作用。感恩,如果有人能帮助!两个坐标之间的距离
输出:
从A点到B点的距离为0.0。点a 到点b的距离为0.0。从点a到点b的距离为0.0。从点a到点b的距离为0.035。从P1到P2的距离 4.242640687119285从P1到P3的距离12.727922061357855
package GC01;
public class Point {
private final double x;
private final double y;
private double distance;
public Point(){
x=0.0;
y=0.0;
}
public Point(double x, double y) {
this.x=x;
this.y=y;
}
public double distanceTo(Point a, Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
distance = Math.sqrt(dx*dx + dy*dy);
return distance;
}
public String toString(){
return "The distance from Point a to Point b is " + distance +".";
}
public static void main(String[] args){
Point p0 = new Point();
Point p1 = new Point(0.0,0.0);
Point p2 = new Point(3.0,3.0);
Point p3 = new Point(9.0,9.0);
System.out.println(p0.toString());
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println(p3.toString());
System.out.println("The distance from p1 to p2 is "+p1.distanceTo(p1,p2));
System.out.println("The distance from p1 to p3 is "+p1.distanceTo(p1,p3));
}
}
我没有看到问题出在哪里,而只是一个建议。对于你的distanceTo函数,你应该只需要1个点的参数。第一点将是你“进入”的点,即这个。第二点将是参数。 – Kindread
其实问题是什么?鉴于你如何输出,你正在得到你应该的价值。从p1到p2的距离是4.24。而p1到p3是12.727,这就是你所得到的。正如Andrew_CS指出的那样,您的困惑可能是您在计算之前输出了缓存距离。 – Kindread
如果回答这个问题,你应该接受一个答案 - 这样它就不会被标记为未解决。 –