【问题标题】:Average length of a one dimensional array in JavaJava中一维数组的平均长度
【发布时间】:2013-03-01 05:50:12
【问题描述】:

我是网站和一般编程新手,请耐心等待。

我的程序必须满足以下条件:

  1. 读取一个正整数 n,后跟 n 点的 (x,y) 坐标,将这些值存储在一个名为 points 的二维数组中,其中包含 n 行和两列。

  2. 创建一个二维数组,其中包含名为距离的n 行和n 列,距离[i][j] = 从点[i] 到点[j] 的距离。

  3. 创建一个长度为n 的一维数组,命名为averages,averages[i] = 行的平均值i 的距离。

  4. 确定并打印n 点中的哪个点的平均距离最短。

我似乎对第 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 要求 avg[i] 是 distance[i][0]..distance[i][n] 的平均值。这与求一维数组的平均值相同,因为对于您正在计算的每个平均值,第一项都是常数。

标签: java arrays average


【解决方案1】:

应该这样做:

public static double average(double[] x)
{
   double avg = 0;
   for (double d: x)
     avg += d;
   avg /= x.length;
   return avg;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2013-03-27
    相关资源
    最近更新 更多