0
我對網站和編程一般都很陌生,所以請耐心等待。Java中一維數組的平均長度
我的程序必須滿足以下條件:
讀取一個正整數
n
,其次是(x,y
)座標的n
點,在二維陣列中存儲這些值命名的點與n
行和兩列。用
n
行和n
列創建一個二維數組,距離[i] [j] =從點[i]到點[j]的距離。創建名爲平均長度爲
n
的一維數組,平均值[i] =距離的行的平均值爲i
。確定並打印哪個點的平均距離最小。
部分我似乎被難倒在部分#3,我將如何計算行的平均距離?
這是我的代碼到目前爲止,如果任何人都可以幫助我完成它,我將不勝感激。同時指出我所擁有的任何錯誤。
import java.util.Scanner;
public class Java
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many points: ");
int n = input.nextInt();
double[][] points = new double[n][2];
for(int i = 0; i < n; i++)
{
//prompt or and get coordinates
//points[i][0] = input.nextDouble();
//points[i][1] = input.nextDouble();
}
double[][] distances = new double[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
distances[i][j] = distance(points[i], points[j]);
double[] averages = new double[n];
for(int i = 0; i < n; i++)
averages[i] = average(distances[i]);
int which_one = minimum_location(averages);
System.out.printf("Point # %d has a smallest average of %f\n", which_one,
averages[which_one]);
}
public static double distance
(double x1, double y1, double x2, double y2)
{
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
{
public static double average(double[] x);
//problem area
}
{
public static int minimum_location(double[] x);
if (shortestDistance > distance);
{
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
#3是要求平均[I]是距離[I] [0] ..距離[I] [N]的平均值。這與要求1d陣列的平均值相同,因爲第一項對於您計算的每個平均值是不變的。 – Thomas 2013-03-01 05:59:57