我的類方法之一的結果總是出現0
。我知道這可能發生,因爲整數部門,我已經嘗試將所需的任何數字鑄造到double
;但它保持0
。問題在於底部的variance
方法。這對我來說很奇怪,因爲Average方法似乎分得很好。使用類方法劃分總是爲零
public class MyArray {
private int[] array;
private int count = 0;
public int length;
public double sum;
public double average;
public double sqSum;
public double variance;
//Constructor to instantiate a new array
public MyArray(int length) {
array = new int[length];
}
public int length(){
return array.length;
}
//getter for count
public int getCount(){
return count;
}
//setter for count
public void setCount(int Count){
this.count = Count;
}
//getter for integers
public int[] getInts(){
return array;
}
//setter for integers
public void setInts(int counter, int input) {
array[counter] = input;
}
public int getArray(int position) {
return array[position];
}
public void setArray(int counter, int element){
array[counter] = element;
}
public int intAt(int index) {
return array[index];
}
//Method to print Arrays
public void printArray() {
System.out.println("\nThe length of the array is "
+ array.length);
for(int i=0; i<array.length; i++)
System.out.println("The array is:" + array[i]);
}
//Method to check if array is sorted
public void isSortedArray() {
for(int i=0; i<array.length; i++)
System.out.println("The array is:" + array[i]);
}
//method to calc sum
public double sum() {
for(int i=0; i<array.length;i++)
sum+= array[i];
return (double)sum;
}
//method to calc Average
public double average() {
average =sum/array.length;
return (double)average;
}
//method to calc sqSum
public double sqSum() {
double sqSum = 0.0;
for(int i=0; i<array.length; i++)
sqSum = sqSum +array[i] * array[i];
return (double)sqSum;
}
//method to calculate variance
public double variance() {
variance = (double)sqSum/array.length;
return (double)variance;
}
}
你曾經賦值給'sqSum'成員變量?如果是這樣,什麼? – Michael
如果我沒有誤解你,我在方法中賦予了0.0到sqSum。 – felipe342
如果你正在談論'sqSum'方法,那麼它有自己的本地'sqSum'變量('double sqSum = 0.0;')。我正在談論'MyArray'的成員變量'sqSum',你試圖用'方差'來分割。 – Michael