当我测试我的代码时,我一直得到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;
}
}
答案 0 :(得分: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];
答案 1 :(得分:1)
问题:
sum += sum + array[i];
不对。使用+=
或在右侧使用总和并使用=
但不能同时使用。{/ li>
答案 2 :(得分:0)
sum += sum + array[i]
应该是:
sum += array[i];
并且在for循环中,从索引0
开始,你不会从长度中减去1它应该是:
for (int i = 0; i < array.length; i++) {
// additional logic
}
答案 3 :(得分:0)
1.更改
Array(int[] array) {
this.array = new int[10];
}
到
Array(int[] array) {
this.array = array;
}
2.Change
sum += sum + array[i];
到
sum += array[i];
3.Change
for (int i = 0; i < array.length - 1; i++)
到
for (int i = 0; i < array.length; i++)
答案 4 :(得分: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;
}
}