java - 如何计算数组中所有非负数的平均值

标签 java average

我在计算平均值时遇到问题 数组中的所有非负数(包括零),否则返回零。以下是我的代码,请帮我检查一下哪些部分是错误的。谢谢。

  public class AverageOfNonNegativeNumbers {

  public static double averageOfNumbers(double[] x) throws Exception {
    double avg = 0.1;
    if (x != null) {
        for (double i = 0.1; i < x.length; i++) {
            if ( x[i]%2 == 0 ) {  //Anyone know how to set avoid calculate for negative numbers?
                avg = avg / x[i];  //This code is calculate total average number. 
            }
        }
    }
    return avg;
}

public static void main(String args[]) {
    double x[] = {1.663, -2.1312, 3.13231, 4.124, -5.551, -6.1312, 7.111, 8.222, -9.01};
    try {
        System.out.println(AverageOfNonNegativeNumbers.averageOfNumbers(x));
    } catch (Exception e) {
        System.out.println("Error!!!");
    }
}
}

最佳答案

定义2个变量来存储非负数的sum和非负数的count

然后遍历数组并检查每个元素是否为非负数。如果非负,则将该值添加到 sum 中,并将 count 加 1。

最后,将sum除以count即可得到平均值。

public static double averageOfNumbers(double[] x) {
    double sum = 0; // Variable to store the sum
    int count = 0; // Variable to keep the count

    if (x != null) {
        for (int i = 0; i < x.length; i++) {
            double value = x[i];
            if (value >= 0) { // Check if the number is non-negative
                sum += value; // Add the value to the current sum
                count++; // Increment the count by 1
            }
        }

    }
    return (count > 0) ? (sum /count) : 0; // Calculate the average if there were any non-negative numbers

}

关于java - 如何计算数组中所有非负数的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58178072/

相关文章:

java - 如果未设置默认值,Gradle 会在哪里生成 JavaDoc?

java - 使用 Collections API 进行随机播放

mysql - DOB 字段的平均年龄 - MySQL/PHP

javascript - 计算任意数量参数的平均值

mysql - 如何从MySQL中获取每分钟两次的平均值

python , Pandas : average every 2 rows together

java事件队列事件调度刷新/陷阱事件

java - 删除 Rest Controller 中的方法 Cors 问题

java - 设置 (PNG) 位图颜色而不是逐像素设置的更快方法

SQL返回最小值与groupby之比