[英]Distance between two coordinates
我正在尝试获取坐标之间的距离,由于某种原因,它似乎不起作用。 感谢任何人都可以提供帮助!
输出:
从点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));
}
}
我看到的一件事是,当您运行主程序时,您在获得积分后四次调用Point.toString()方法。 执行此操作时,尚未设置distance变量,因为尚未调用distanceTo方法。
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());
发生这些Point.toString调用时,尚未调用distanceTo方法,因此尚未为任何这些点设置距离。
您会在最后两行输出数字,因为您调用了distanceTo方法。
这对您有用吗?
public class Point {
private final double x;
private final double y;
public Point() {
x = 0.0;
y = 0.0;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double distanceTo(Point other) {
double dx = other.x - this.x;
double dy = other.y - this.y;
double distance = Math.sqrt(dx * dx + dy * dy);
return distance;
}
public String toString() {
return x + "/" + y;
}
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(p2));
System.out
.println("The distance from p1 to p3 is " + p1.distanceTo(p3));
}
}
我从您的班级中删除了distance
变量,因为在一个点和另一个点之间只能有一个距离。 一个点本身没有距离。
我也改变distanceTo
:当你调用p1.distanceTo(p2)
你传递的参考p2
到p1
。 现在,p2在distanceTo
方法中称为other
。
编写this.x
只是编写x
一种更详细的方法。 我想弄清楚这个x
变量属于distanceTo
方法的接收者(在这种情况下为p1
)。
最终,我将toString
更改为可打印您的点的X和Y坐标。 在Java实例中,变量(例如,已删除的distance
始终以0初始化。这就是为什么始终打印px.toString()
原因
点a到点b的距离是0.0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.