正如标题所示,我正在做一个家庭作业,我们仅限于使用多维数组来创建一个程序,该程序可以在三维空间中找到彼此最近的两个点。到目前为止,我的代码看起来像这样(从我的教科书和我自己的代码中的示例混合):
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1, p3 = 2;
double shortestDistance = distance(points[p1][0] , points[p1][1] , points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , points[j][0] , points[j][1] , points[j][2] , points[i][2] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0] + "," + points[p1][1] +
and (" + points[p2][0] + "," );
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) + ((z2 - z1) * (z2 - z1)));
}
}
我最需要帮助的是弄清楚如何比较这些点。我不认为我解决这个问题的方法是最好的方法。
谢谢你们的帮助。我现在连续 2 天睡 2 小时,所以请原谅任何愚蠢的问题或草率的代码。
******
我想我明白了:
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1;
double shortestDistance = distance(points[p1][0] , points[p1][1] , points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , points[j][0] , points[j][1] , points[j][2] , points[i][2] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0] + "," + points[p1][1] + "," + points[p1][2] +
") and (" + points[p2][0] + "," + points[p2][1] + "," + points[p2][2] + ")");
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) + ((z2 - z1) * (z2 - z1)));
}
}
输入被输入、处理,然后输出两个最近的点。仅作为参考,当:(-1,0,3),(-1,-1,-1),(4,1,1),(2,0.5,9),(3.5,1.5,3) ,(-1.5,4,2),(5.5,4,-0.5) 被输入,结果似乎是 (-1,0,3) 和 (4,1,1)。有人可以为我确认一下。
如果这不是跟进我自己的问题的方法,我很抱歉。在这些斜坡上的第一天,我仍在学习绳索。