public class Exercise08_07 { public static void main(String[] args) { double[][] points = { {-1, 0, 3}, {-1, -1, -1}, {4, 1, 1}, {2, 0.5, 9}, {3.5, 2, -1}, {3, 1.5, 3}, {-1.5, 4, 2}, {5.5, 4, -0.5}}; int p1 = 0, p2 = 1;//存储距离最小的两点所在二维数组下标,暂定下标0和1的坐标距离最小 double shortestDistance = distance(points[p1][0],points[p1][1],points[p1][2],points[p2][0],points[p2][1],points[p2][2]);//暂定下标0和1的坐标距离最小 for (int i = 0; i < points.length; i++){//计算i下标的坐标与其后位下标(j = i + 1)的坐标距离且比较 for (int j = i + 1; j < points.length; j++){ double distance = distance(points[i][0],points[i][1],points[i][2],points[j][0],points[j][1],points[j][2]);//计算两点距离 if (shortestDistance > distance){//如果当前两点距离最小则更新 shortestDistance = distance; p1 = i;//p1和p2用于存储当前彼此距离最小的两个下标 p2 = j; } } } 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)); } }
java黑皮书课后习题8.7
最新推荐文章于 2022-12-30 06:07:54 发布