(中心城市)给定一组城市,中心城市是和所有其他城市之间具有最短距离的城市。编写一个Java程序,提示用户输人城市的数目以及城市的位置(坐标),找到中心城市以及和所有其他城市的总距离。

package chapter08;

import java.util.Scanner;

/**
 * @author mazouri
 * @create 2020-03-31 22:00
 */
public class Question21 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of cities: ");
        int numberOfCities = scanner.nextInt();
        System.out.print("Enter the coordinates of the cities: ");
        double[][] location = new double[numberOfCities][2];
        //输入数据
        for (int i = 0; i < location.length; i++) {
            location[i][0] = scanner.nextDouble();
            location[i][1] = scanner.nextDouble();
        }

        double minTotal = totalDistance(location, 0);
        int minIndex = 0;
        for (int i = 0; i < location.length; i++) {
            double total = totalDistance(location, i);

            if (minTotal > total) {
                minTotal = total;
                minIndex = i;
            }
        }
        System.out.println("The central city is at (" +
                location[minIndex][0] + ", " + location[minIndex][1] + ")");
        System.out.println("The total distance to all other cities is " +
                minTotal);
    }

    /**
     * @param location 存放城市的坐标
     * @param i        与其他城市计算距离的某一城市位置
     * @return 某一点与其他点的总距离
     */
    public static double totalDistance(double[][] location, int i) {
        double totalDistance = 0;
        for (int j = 0; j < location.length; j++) {

            //二维数据是一维数组的数组
            totalDistance += distance(location[i], location[j]);
        }
        return totalDistance;
    }

    /**
     * @param city1 本次不变的城市
     * @param city2 一直变化的城市
     * @return 与其他城市的长度
     */
    public static double distance(double[] city1, double[] city2) {

        return Math.sqrt((city1[0] - city2[0]) * (city1[0] - city2[0]) +
                (city1[1] - city2[1]) * (city1[1] - city2[1]));
    }
}

在这里插入图片描述

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马走日mazouri

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值