我期望得到3.5來自平均方法的結果,但我得到3.0。不知道爲什麼。我期望Double能給我結果,但是沒有。 java.util.ArrayList;如何獲得Java中的平均方法以提供正確的輸出
public class Hangman {
public static void main(String[] args) {
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(3);
intList.add(2);
intList.add(7);
intList.add(2);
System.out.println("The variance number is : ");
System.out.println(sum(intList));
System.out.println(intList.size());
System.out.println(average(intList));
}
public static int sum(ArrayList<Integer> intList) {
int sum = 0;
for (int counter = 0; counter < intList.size(); counter++) {
sum = sum + intList.get(counter);
}
return sum;
}
public static double average(ArrayList<Integer> intList) {
double avg = sum(intList)/(intList.size());
return avg;
}
public static ArrayList<Double> subtract(ArrayList<Integer> intList) {
ArrayList<Double> subtracted = new ArrayList<Double>();
for (double subtract : intList) {
subtracted.add((double) (subtract - average(intList)));
}
return subtracted;
}
public static double variance(ArrayList<Integer> intList) {
double sumDiffsSquared = 0.0;
double avg = average(intList);
for (int value : intList) {
double diff = value - avg;
diff *= diff;
sumDiffsSquared += diff;
}
return (sumDiffsSquared/(intList.size() - 1));
}
}