2015-10-17 66 views
0

我期望得到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)); 
    } 

} 

回答

1

sum需要返回雙,否則當你做一個

sum(intList)/(intList.size()); 
average方法

,它截斷下來計算爲整數的值,然後把該值雙形式。

0

你的函數需要返回一個double值。

改變你的方法

public static double sum(ArrayList<Integer> intList) { 
    double sum = 0; 
    for (int counter = 0; counter < intList.size(); counter++) { 
     sum = sum + intList.get(counter); 
    } 
    return sum; 
    } 

,你應該做的罰款。

0

儘管avg的類型是雙倍,sum()方法正在返回一個整數值。所以你有一個雙從sum()方法

0

double avg =(double)sum(intList)/(intList.size());