import java.util.*; public class CenterTree { public static final int N = 5; // 中心树加上最近的四个点一共有5个点 public static void main(String[] args) { // 从控制台读取中心点坐标 Scanner scanner = new Scanner(System.in); System.out.print("请输入中心点
时间: 2024-04-27 16:20:11 浏览: 113
的横坐标:"); int centerX = scanner.nextInt(); System.out.print("请输入中心点的纵坐标:"); int centerY = scanner.nextInt(); // 存储每个点的距离 double[] distances = new double[N]; // 从控制台读取每个点的坐标,并计算它们与中心点的距离 for (int i = 0; i < N; i++) { System.out.print("请输入第" + (i+1) + "个点的横坐标:"); int x = scanner.nextInt(); System.out.print("请输入第" + (i+1) + "个点的纵坐标:"); int y = scanner.nextInt(); distances[i] = Math.sqrt(Math.pow(x-centerX, 2) + Math.pow(y-centerY, 2)); } // 找到距离中心点最近的四个点的下标 int[] nearestIndices = new int[4]; for (int i = 0; i < 4; i++) { int nearestIndex = -1; double nearestDistance = Double.MAX_VALUE; for (int j = 0; j < N; j++) { if (distances[j] < nearestDistance && !isIndexUsed(j, nearestIndices)) { nearestIndex = j; nearestDistance = distances[j]; } } nearestIndices[i] = nearestIndex; } // 输出结果 System.out.print("中心树为中心点(" + centerX + "," + centerY + ")和最近的四个点:"); for (int i = 0; i < 4; i++) { int index = nearestIndices[i]; System.out.print("(" + index + "," + distances[index] + ") "); } } /** * 判断一个下标是否已经被使用 */ private static boolean isIndexUsed(int index, int[] indices) { for (int i = 0; i < indices.length; i++) { if (indices[i] == index) { return true; } } return false; } }
请问这段Java代码的作用是什么?
阅读全文