如何让Average方法在Java中提供正确的输出

时间:2015-10-17 05:21:37

标签: java

我期望从平均方法得到3.5,但我得到3.0。不知道为什么。我希望Double给我结果,但没有。 的java.util.ArrayList;

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));
  }

}

4 个答案:

答案 0 :(得分:1)

sum需要返回一个double,否则当你执行

sum(intList) / (intList.size());

average方法中,它会将计算出的值截断为整数,然后将该值设置为double格式。

答案 1 :(得分:0)

您的函数需要返回一个double值。

将您的方法更改为

compile 'com.github.bumptech.glide:glide:3.6.1'

你应该做得很好。

答案 2 :(得分:0)

虽然avg的类型是double,但sum()方法返回的是Integer值。所以你从sum()方法

返回一个双精度数

答案 3 :(得分:0)

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