-1

当我测试我的代码时,我不断得到 0 作为以下代码的总和和平均值,但它可以编译。我不确定我做错了什么。

public class Array {
  int array[];
  int sum;

  Array(int[] array) {
    this.array = new int[10];

  }
  public int sum(){
      for (int i = 0; i < array.length - 1; i++)
         sum += sum + array[i];
      return sum;
    }
  public double average() {
      for (int i = 0; i < array.length - 1; i++)
         sum += sum + array[i];
      int average = sum / array.length;
      return average;
  }
}
4

5 回答 5

7
   Array(int[] array) {
     this.array = new int[10];      //The Problem is here

   }

用这个

   Array(int[] array) {
      this.array = array;

   }

并将总和更改为

  sum = sum + array[i];

  or

  sum += array[i];
于 2013-09-18T01:06:13.643 回答
1

问题:

  • 您所写的数组仅包含零。
  • sum += sum + array[i];的不对。要么使用,要么+=在右边有总和并使用=,但不能同时使用。
  • 您的平均值应该将分子或分母转换为双倍,因此您进行双除法而不是整数除法。
于 2013-09-18T01:05:41.253 回答
0

在这里你有一些错误......

public class Array {
    int array[];
    int sum;

    Array(int[] array) {
        this.array = new int[10];
        // this is write but wrong because if you are getting array of int as an argument then why you are not using it. here you can write like this
       // this.array = array;
    }
    public int sum(){
        for (int i = 0; i < array.length - 1; i++)
            sum += sum + array[i];
            // what is this? completely wrong logic for adding here you can use like this 
            // sum += array[i]   or you can use
            // sum = sum + array[i]
            return sum;
    }
    public double average() {
        for (int i = 0; i < array.length - 1; i++)
            sum += sum + array[i];
            // same mistake again
            // one more point is if you have called sum() function then sum(variable) is already having adding of arrays that time you can not summing up again

            int average = sum / array.length;
            return average;
     }
}
于 2013-12-20T05:16:04.633 回答
0
sum += sum + array[i]

应该 :

sum += array[i];

在 for 循环中,您不会从长度中减去 1,因为您从索引 0 开始

它应该是 :

for (int i = 0; i < array.length; i++) {
     // additional logic
}
于 2013-09-18T01:29:54.333 回答
0

1.改变

Array(int[] array) {
this.array = new int[10];
}

Array(int[] array) {
  this.array = array;
}

2.改变

 sum += sum + array[i];

sum += array[i];

3.改变

for (int i = 0; i < array.length - 1; i++)

for (int i = 0; i < array.length; i++)
于 2013-09-18T07:52:34.727 回答