如何计算 Java 中我的原始点和提供点之间的距离
How to compute distance between my original and supplied point in Java
public class Point {
private double X, Y;
public Point() {
setPoint(0.0,0.0);
}
public Point (double X, double Y) {
setPoint(X,Y);
}
public void setPoint(double X, double Y) {
this.X = X;
this.Y = Y;
}
public double getX() {
return this.X;
}
public double getY() {
return this.Y;
}
/**
* Compute the distance of this Point to the supplied Point x.
*
* @param x Point from which the distance should be measured.
* @return The distance between x and this instance
*/
public double distance(Point x) {
double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
return Math.sqrt(d);
}
我正在尝试计算我的 "original point" 和我提供的点 x 的距离。我不确定我是否做对了。我主要关心的是:
How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.
感谢任何帮助。 PS 我是 Java 的新手。
所以我也在考虑为我的点分配函数内的值:
public double distance(Point x) {
Point x = new Point(X,Y);
double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
return Math.sqrt(d);
}
这样可以吗?
您没有在参数中使用。
public double distance(Point other) {
double d = Math.pow(other.getX()- getX(), 2) + Math.pow(other.getY() - getY(), 2);
return Math.sqrt(d);
}
在方法 distance 中,您将另一个点作为变量传递,名称为 x
(不是一个很好的名称),并且可以使用该变量访问其字段和方法:
public double distance(Point x) {
double currentPointX = this.getX();
double otherPointX = x.getX();
}
Y 值也是如此,然后您可以使用这些值进行数学运算。
Math.sqrt((x1-xa)(x1-xa) + (j1-j)(j1-j))
如果您有如下 class:
public class Point {
private double x;
private double y;
...constructors and methods omitted
}
要计算您的点与另一个点之间的距离,您可以使用 java 标准方法 Math.hypot,如下所示:
public double distance(Point other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}