首页 / JAVA / 找出距离最近的点对,用java实现
找出距离最近的点对,用java实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了找出距离最近的点对,用java实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1794字,纯文字阅读大概需要3分钟。
内容图文
一.介绍
程序提示用户输人点的个数。从控制台读取多个点,并将它们存储在一个名为points的二维数组中。程序使用变量shortestDistance来存储两个距离最近的点,而这两个点在points数组中的下标都存储在p1和p2中。对每一个索引值为i的点,程序会对所有的j>i计算points[i]和points[j]之间的距离。只要找到比当前最短距离更短的距离,就更新变量shortestDistance以及p1和p2。
二.代码
package com.zhuo.base;
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();
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和p2是点数组中的索引*/
int p1 = 0;
int p2 = 1;
double shotestDistance = distance(points[p1][0],points[p1][1],points[p2][0],points[p2][1]);//初始化最短距离
/*计算每两点的距离*/
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 (shotestDistance > distance) {
p1 = i;
p2 = j;
shotestDistance = distance;
}
}
}
System.out.println("The closest tow points are: " + "(" + points[p1][0] + "," + points[p1][1] + ")"
+ " and " + "(" + points[p2][0] + "," + points[p2][1] + ")");
}
/*计算两点(x1,y2)和(x2,y2)之间的距离的方法*/
public static double distance(double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}
三.结果显示
Enter the number of points: 8
Enter 8 points: -1 3 -1 -1 1 1 2 0.5 2 -1 3 3 4 2 4 -0.5
The closest tow points are: (1.0,1.0) and (2.0,0.5)
Process finished with exit code 0
内容总结
以上是互联网集市为您收集整理的找出距离最近的点对,用java实现全部内容,希望文章能够帮你解决找出距离最近的点对,用java实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。