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]));
}
}
(中心城市)給定一組城市,中心城市是和所有其他城市之間具有最短距離的城市。編寫一個Java程序,提示用戶輸人城市的數目以及城市的位置(座標),找到中心城市以及和所有其他城市的總距離。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.