使用参数作为标识符?
Using Parameters as Identifiers?
这似乎是一个愚蠢的问题,但我是 Java 的新手。我正在尝试找出两点的距离。 方法摘要:计算这个点和另一个点之间的距离 当我尝试编译时出现错误:无法找到符号(在我的双 dx 和双 dy 中)。如果有人可以提供帮助,我们将不胜感激。下面是我的代码。
public class CartPoint implements Point{
private Double x;
private Double y;
public CartPoint (double x, double y){
this.x = x;
this.y = y;
}
public double x(){
return x;
}
public double y(){
return y;
}
public double distanceFrom(Point other){
double dx = (other.x - this.x);
double dy = (other.y - this.y);
return Math.sqrt(dx*dx + dy*dy);
}
//界面
public interface Point{
double x();
double y();
}
x
和 y
是 CartPoint
class 的成员,而不是 Point
class 的成员,因此您应该将其用作参数 class:
public double distanceFrom(CartPoint other) {
或者,您可以在 Point
接口中添加 getX()
和 getY()
方法并使用它们:
public double distanceFrom(Point other){
double dx = (other.getX() - getX());
double dy = (other.getY() - getY());
return Math.sqrt(dx*dx + dy*dy);
}
编辑:
现在您已经编辑了问题并在界面中显示了 x()
和 y()
方法,这就是您应该使用的方法:
public double distanceFrom(Point other){
double dx = (other.x() - x());
double dy = (other.y() - y());
return Math.sqrt(dx*dx + dy*dy);
}
我认为这会起作用并且不太容易出现舍入错误:
public double distanceFrom(Point other){
double distance = 0.0;
double dx = Math.abs(other.x() - this.x());
double dy = Math.abs(other.y() - this.y());
if (dx > dy) {
double ratio = dy/dx;
distance = dx*Math.sqrt(1.0+ratio*ratio);
} else {
double ratio = dx/dy;
distance = dy*Math.sqrt(1.+ratio*ratio);
}
return distance;
}
请注意,此距离公式仅适用于二维笛卡尔坐标系。球坐标系上的距离差别很大
这似乎是一个愚蠢的问题,但我是 Java 的新手。我正在尝试找出两点的距离。 方法摘要:计算这个点和另一个点之间的距离 当我尝试编译时出现错误:无法找到符号(在我的双 dx 和双 dy 中)。如果有人可以提供帮助,我们将不胜感激。下面是我的代码。
public class CartPoint implements Point{
private Double x;
private Double y;
public CartPoint (double x, double y){
this.x = x;
this.y = y;
}
public double x(){
return x;
}
public double y(){
return y;
}
public double distanceFrom(Point other){
double dx = (other.x - this.x);
double dy = (other.y - this.y);
return Math.sqrt(dx*dx + dy*dy);
}
//界面
public interface Point{
double x();
double y();
}
x
和 y
是 CartPoint
class 的成员,而不是 Point
class 的成员,因此您应该将其用作参数 class:
public double distanceFrom(CartPoint other) {
或者,您可以在 Point
接口中添加 getX()
和 getY()
方法并使用它们:
public double distanceFrom(Point other){
double dx = (other.getX() - getX());
double dy = (other.getY() - getY());
return Math.sqrt(dx*dx + dy*dy);
}
编辑:
现在您已经编辑了问题并在界面中显示了 x()
和 y()
方法,这就是您应该使用的方法:
public double distanceFrom(Point other){
double dx = (other.x() - x());
double dy = (other.y() - y());
return Math.sqrt(dx*dx + dy*dy);
}
我认为这会起作用并且不太容易出现舍入错误:
public double distanceFrom(Point other){
double distance = 0.0;
double dx = Math.abs(other.x() - this.x());
double dy = Math.abs(other.y() - this.y());
if (dx > dy) {
double ratio = dy/dx;
distance = dx*Math.sqrt(1.0+ratio*ratio);
} else {
double ratio = dx/dy;
distance = dy*Math.sqrt(1.+ratio*ratio);
}
return distance;
}
请注意,此距离公式仅适用于二维笛卡尔坐标系。球坐标系上的距离差别很大