计算 x y 的最近值
计算xy的最近值。
代码如下:
package Day05;
import java.util.Arrays;
public class FindNearestPoints { public static void main(String[] args) {
double[][] points = {
{-1, -3}, {-1, -1}, {1, 1}, {2, 0.5}, {2, -1}, {3, 3}, {4, 2}, {4, -0.5}
};
double minDistance = distance(points[0], points[1]);
int minPoint1 = 0;
int minPoint2 = 1;
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
if (distance(points[i], points[j]) < minDistance) {
minDistance = distance(points[i], points[j]);
minPoint1 = i;
minPoint2 = j;
}
}
}
System.out.println("Min distance is: " + minDistance);
System.out.println("They are: " + Arrays.toString(points[minPoint1])
+ Arrays.toString(points[minPoint2]));
}
private static double distance(double[] ds1, double[] ds2) {
return Math.sqrt(square(ds1[0] - ds2[0]) + square(ds1[1] - ds2[1]));
}
private static double square(double num) {
return Math.pow(num, 2);
}
}