创建一个方法来返回数组的平均值

时间:2013-03-26 02:07:20

标签: java

我正在尝试在传递数组对象数组的类中创建一个静态方法,并返回数组中对象的平均值。

public static double calcAverage() {
  int sum = 0;
  for (int i=0; i < people.length; i++)
            sum = sum + people[i];
  double calcAverage() = sum / people.length
     System.out.println(people.calcAverage());
}

代码正在编译错误,但我正朝着正确的方向前进吗?

3 个答案:

答案 0 :(得分:1)

public static double calcAverage() {
  int sum = 0;
  for (int i=0; i < people.length; i++)
            sum = sum + people[i];
  double calcAverage() = sum / people.length
     System.out.println(people.calcAverage());
}

更改

  double calcAverage() = sum / people.length

  double average = sum / (double)people.length;

(声明新变量的正确方法)

更改

     System.out.println(people.calcAverage());

  return average;

(如果要打印调用函数的结果,则应始终在函数外部执行此操作,例如在调用函数并存储返回的结果后在main中执行此操作)

所以我们有:

public static double calcAverage() {
  int sum = 0;
  for (int i=0; i < people.length; i++)
  {
       sum = sum + people[i];
  }
  double average = sum / (double)people.length;
  return average;
}

答案 1 :(得分:1)

你的亲密关系。我看到了一些错误。

首先你的总和=总和+人[i];

people [i]返回的是对象而不是整数,因此将对象添加到整数不起作用。

第二,你在calcAverage方法中调用calcAverage(),这可能不是你想要做的。这样做称为递归,但我认为你应该在calcAverage()之外调用方法。

答案 2 :(得分:1)

// pass people as a parameter
public static double calcAverage(int[] people) {
   // IMPORTANT: this must be a double, otherwise you're dividing an integer by an integer and you will get the wrong answer
   double sum = 0;
   for (int i=0; i < people.length; i++) {
        sum = sum + people[i];
   }
   // remove the ()
   double result = sum / people.length;
   System.out.println(result);

   // return something
   return result;
}


// example
int[] myPeople = {1,2,3,4,5,6,7,8};
double myPeopleAverage = calcAverage(myPeople);