java黑皮书课后习题8.7

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));
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值