(中心城市)给定一组城市,中心城市是和所有其他城市之间具有最短距离的城市。编写一个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]));
    }
}

在这里插入图片描述

发布了4 篇原创文章 · 获赞 14 · 访问量 221

猜你喜欢

转载自blog.csdn.net/weixin_46215617/article/details/105234935