package test;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Manlifa {
public static int n;
/*
* 注,此处若没有为数组进行初始化则会出现空指针异常,即仅仅声明了数组x和y,
* 声明了数组,但是并没有为他们分配相应的内存空间,此时,他们仅仅是一个地址罢了
*/
public static double x[] = new double[100];
public static double y[] = new double[100];
public Manlifa() {
}
public static void choose() {
int i;
int j;
int indexi = 0;
int indexj = 0;
double mindistance = (double) 800;
double d;
DecimalFormat df = new DecimalFormat("0.00");
for (i = 0; i < n - 1; i++)
for (j = i + 1; j < n; j++) {
d = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
if (d < mindistance) {
mindistance = d;
indexi = i;
indexj = j;
}
}
System.out.println(
"距离最短的两个点是," + "(" + x[indexi] + "," + y[indexi] + ")" + "(" + x[indexj] + "," + y[indexj] + ")");
System.out.printf("最短距离为:");
System.out.printf(df.format(Math.sqrt(mindistance)));
}
public static void main(String arg[]) {
int ch = 0;
int i = 0;
System.out.println("请输入若干个点:");
Scanner read = new Scanner(System.in);
Manlifa m = new Manlifa();
while (ch != 1) {
x[i] = read.nextDouble();
y[i] = read.nextDouble();
ch = read.nextInt();
n++;
i++;
}
n = n - 1;
m.choose();
}
}
蛮力法实现最近对问题
最新推荐文章于 2023-02-28 15:59:26 发布