有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

    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) 个答案

  1. # 1 楼答案

    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;
    
  2. # 2 楼答案

    创建另一个变量(计数器),当发现非零值时,该变量将递增1。然后用这个变量除以总数

  3. # 3 楼答案

    您可以使用高级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();