【发布时间】:2013-10-06 21:47:14
【问题描述】:
我正在尝试获取坐标之间的距离,但由于某种原因它似乎不起作用。如果有人能提供帮助,不胜感激!
输出:
a 点到 b 点的距离为 0.0。到a点的距离 到点 b 为 0.0。 a 点到 b 点的距离为 0.0。这 a 点到 b 点的距离为 0.0。 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 个点作为参数。第一点将是你“在”的点,即这个。第二点将是参数。
-
究竟是什么问题?鉴于您的输出方式,您将获得应有的值。从 p1 到 p2 的距离是 4.24。 p1 到 p3 是 12.727,这就是你得到的。正如 Andrew_CS 指出的那样,您的困惑可能是您在计算之前输出了缓存的距离。
-
如果这个问题得到了回答,您应该接受一个答案 - 这样它就不会被标记为未解决。