数组中非零值的平均值(Java)

时间:2014-04-28 00:21:35

标签: java arrays average

我正在尝试查找数组的平均值,但我只希望包含大于零的值。这就是我现在所拥有的:

    double total = 0;
    double average;

    for (int index = 1; index < monthlyVisitors.length; index++)
    {
        if (monthlyVisitors[index] > 0)
            total += monthlyVisitors[index];
    }

    average = total / monthlyVisitors.length;

此时我已经尝试过百万种不同的东西了。我知道这很简单,但我无法弄清楚。谢谢!

3 个答案:

答案 0 :(得分:2)

if块中添加一个计数器,然后将total除以count

此外,您从索引1开始,您可能不想这样做,因为数组是0索引的(它们从0开始而不是1)。

int count = 0;
double total = 0;
double average;

//Are you sure you want this to start at index 1?
for (int index = 1; index < monthlyVisitors.length; index++)
{
    if (monthlyVisitors[index] > 0)
    {
        total += monthlyVisitors[index];
        count++;
    } 
}

average = total / count;

答案 1 :(得分:2)

您可以使用高级for loop来迭代monthlyVisitors

它摆脱了int index

的需要
    int total = 0;
    int nonzeroMonths = 0;

    for(int visitors : monthlyVisitors)
        if(visitors > 0)
        {
            total += visitors;

            nonzeroMonths++;
        }

    double average = ( (double) total / nonzeroMonths );

或者你可以摆脱0次访问的月份并使用lambda(Java 1.8)对列表求和,除以大小

    ArrayList<Integer> list = 
            new ArrayList<>(monthlyVisitors.length);

    for(int item : monthlyVisitors)
        if(item > 0) list.add(item);

    double average = 
        list.parallelStream().filter(n -> n > 0)
                             .mapToDouble(n -> n).sum() / list.size();

答案 2 :(得分:1)

创建另一个变量(计数器),当您找到非零值时,该变量加1。然后用这个变量除以总数。

相关问题