Java在坐标系中找出距离最近的点

x33g5p2x  于2022-05-24 转载在 Java  
字(1.4k)|赞(0)|评价(0)|浏览(400)

在有限点中找出距离最近的点,要求用二维数组且为浮点型(Double)编写,编写一个distance方法计算距离在主方法中来比较

输入:输入点的个数和坐标点(不需要括号和逗号)

  1. 8
  2. -1 3 -1 -1 1 1 2 0.5 2 -1 3 3 4 2 4 -0.5

输出:输出距离最近的点的坐标

  1. Enter the number of points:
  2. Enter points:
  3. The closest two points are (1.0,1.0) and (2.0,0.5)
  1. import java.util.Scanner;
  2. public class FindNearestPoints {
  3. public static void main(String[] args) {
  4. Scanner input = new Scanner(System.in);
  5. System.out.print("Enter the number of points: ");
  6. int numberOfPoints = input.nextInt();
  7. //Create an array to store points
  8. double[][] points = new double[numberOfPoints][2];
  9. System.out.print("Enter " + numberOfPoints + "points: ");
  10. for (int i = 0; i < points.length; i++) {
  11. points[i][0] = input.nextDouble();
  12. points[i][1] = input.nextDouble();
  13. }
  14. //p1 and p2 are the indices in the points array
  15. int p1 = 0, p2 = 1;
  16. double shortestDistance = distance(points[p1][0],points[p1][1],points[p2][0],points[p2][1]);
  17. //Compute distance for every two points
  18. for (int i = 0; i < points.length; i++) {
  19. for (int j = i + 1; j < points.length; j++) {
  20. double distance = distance(points[i][0],points[i][1],points[j][0],points[j][1]);
  21. if (shortestDistance > distance){
  22. p1 = i;
  23. p2 = j;
  24. shortestDistance = distance;
  25. }
  26. }
  27. }
  28. //Display result
  29. System.out.println("The closest two points are " + "(" + points[p1][0] + ","
  30. + points[p1][1] + ") and (" + points[p2][0] + "," + points[p2][1] + ")");
  31. }
  32. public static double distance(double x1,double y1,double x2,double y2){
  33. return Math.sqrt((x2 - x1)*(x2 - x1) + (y2-y1)*(y2-y1));
  34. }
  35. }

相关文章

最新文章

更多