蛮力法实现最近对问题

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();

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值