閱讀以下說明和 Java 程序,填充程序中的空缺,將解答填入答題紙的對應欄內。
【說明】
下面的程序用來計算并尋找平面坐標系中給定點中最近的點對(若存在多對,則輸出其中的一對即可)。程序運行時,先輸入點的個數和一組互異的點的坐標,通過計算每對點之間的距離,從而確定出距離最近的點對。例如,在圖6-1所示的8個點中,點(1,1)與(2,0.5)是間距最近的點對。
【Java代碼】
import java.util.Scanner;
class GPoint
{
private double x ,y;
public void setX(double x) { this.x = x; }
public void setY(double y) { this.y = y; }
public double getX( ) { return this.x; }
public double getY() { return this.y; }
}
class FindNearestPoints {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" 輸入點的個數: ");
int numberOfPoints = input.nextInt( );
(1)points = new GPoint[numberOfPoints); //創(chuàng)建保存點坐標
的數組
System.out.print("請輸入" + numberOfPoints + "個點的坐標: ");
for (int i = 0; i < points.length; i++) {
points [i] = (2);
points[i].setX(input.nextDouble( ));
points[i].setY(input.nextDouble( ));
}
FindNearestPoints fnp = new FindNearestPoints( );
int p1 = 0 ,p2 = 1; / / p1 和 p2 用于表示距離最近的點對在數組中的下標
double shortestDistance fnp.getDistance (points [p1],points[p2]);
//計算每一對點之間的距離
for (int i = 0; i < points.length; i++)
{
for (int j = i + 1; j < (3); j++)
{
double tmpDistance = fnp.(4)
//計算兩點間的距離
if ( (5))
{
p1= i;
p2 = j;
shortestDistance = tmpDistance;
}
}
}
System.out.println(" 距離最近的點對是(" +
points[p1].getX( ) + "," + points[p1].gety( ) + ")和(" +
points[p2] .getX( ) + ", " + points[p2] .gety( ) + ")");
}
public double getDistance(GPoint pt1,GPoint pt2)
{
return Math. sqrt ((pt2.getX ( ) - pt1.getX ( )) * (pt2.getX ( ) -pt1.getX ( ))
+ (pt2.gety( ) - pt1.getY( )) * (pt2.getY( ) - pt1.getY( )));
}
}