在有限点中找出距离最近的点,要求用二维数组且为浮点型(Double)编写,编写一个distance方法计算距离在主方法中来比较
输入:输入点的个数和坐标点(不需要括号和逗号)
8
-1 3 -1 -1 1 1 2 0.5 2 -1 3 3 4 2 4 -0.5
输出:输出距离最近的点的坐标
Enter the number of points:
Enter points:
The closest two points are (1.0,1.0) and (2.0,0.5)
import java.util.Scanner;
public class FindNearestPoints {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of points: ");
int numberOfPoints = input.nextInt();
//Create an array to store points
double[][] points = new double[numberOfPoints][2];
System.out.print("Enter " + numberOfPoints + "points: ");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
}
//p1 and p2 are the indices in the points array
int p1 = 0, p2 = 1;
double shortestDistance = distance(points[p1][0],points[p1][1],points[p2][0],points[p2][1]);
//Compute distance for every two points
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0],points[i][1],points[j][0],points[j][1]);
if (shortestDistance > distance){
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
//Display result
System.out.println("The closest two points are " + "(" + points[p1][0] + ","
+ points[p1][1] + ") and (" + points[p2][0] + "," + points[p2][1] + ")");
}
public static double distance(double x1,double y1,double x2,double y2){
return Math.sqrt((x2 - x1)*(x2 - x1) + (y2-y1)*(y2-y1));
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://lebron.blog.csdn.net/article/details/124934604
内容来源于网络,如有侵权,请联系作者删除!