gpt4 book ai didi

java - 计算 2D 和 3D 中 2 点之间的距离

转载 作者:行者123 更新时间:2023-12-01 22:56:34 26 4
gpt4 key购买 nike

我只是想解决一个非常简单的问题,但我有一些小问题。希望您能快速帮助初学者;)

我有 2 个类“Point”和“Point3D”,如下所示:

public class Point {
protected double x;
protected double y;

Point(double xCoord, double yCoord){
this.x = xCoord;
this.y = yCoord;
}

public double getX(){
return x;
}

public double getY(){
return y;
}

public static double distance(Point a, Point b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}

public static void main(String[] args) {
Point p1 = new Point(2,2);
Point p2 = new Point(5,6);
System.out.println("Distance between them is " + Point.distance(p1, p2));
}
}

还有这个:

public class Point3D extends Point {
protected double z;

Point3D(double x, double y, double zCoord){
super(x, y);
this.z = zCoord;
}

public double getZ(){
return z;
}

public static double distance(Point p1, Point p2){
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
double dz = p1.z - p2.z;
return Math.sqrt(dx * dx + dy * dy + dz *dz);
}

public static void main(String[] args) {
Point3D p1 = new Point3D(-4,2,5);
Point3D p2 = new Point3D(1,3,-2);
System.out.println("Distance between them is " + Point3D.distance(p1, p2));
}
}

我现在的问题是:如果我像这样保留我的代码,我的 Eclipse 会说“z 无法解析为字段”,作为一个可能的解决方案,我应该在我的类“Point”中创建它。完成此操作后,“Point3D”类会编译,但不会计算出正确的答案..

问候,

最佳答案

将 Point3D 距离方法的签名更改为:

public static double distance(Point3D p1, Point3D p2){

参数只有 Point 类型,没有 z

关于java - 计算 2D 和 3D 中 2 点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23937825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com