【问题标题】:How to calculate the average of all the non-negative numbers in the array如何计算数组中所有非负数的平均值
【发布时间】:2019-10-06 10:55:39
【问题描述】:

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

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

【问题讨论】:

  • 也将int avg 转换为float/double。
  • “否则返回零”,但“否则”的条件是什么?而且“我有问题”不是很有帮助/描述性

标签: java average


【解决方案1】:

定义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

}

【讨论】:

  • 我知道你抄袭了,但throws Exception 是干什么用的?
  • 哦! :) 解决它。谢谢!
  • 你是对的。谢谢 Udith Gunaratna 先生帮我解决这个问题!
【解决方案2】:

以下是问题:

a.您正在尝试访问 x[i],但 i 需要为 integer 类型,而您的类型为 double

b. x[i]%2 == 0 检查数字是否为偶数。需要将其更改为x[i] &gt;= 0

c。计算平均值的逻辑不正确。

public class AverageOfNonNegativeNumbers {

  public static double averageOfNumbers(double[] x) {
    int elements = 0;
    double sum = 0;
    if (x != null) {
        for (int i = 1; i < x.length; i++) {
            if ( x[i] >= 0 ) {  // changed this check if number is negative or not
                sum += x[i];  //This code calculates total sum of all non-negative numbers
                elements++;     // and also how many of such no exists
            }
        }
    }
    return sum/elements;
}

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

【讨论】:

    【解决方案3】:

    您正在尝试使用 double 作为数组的索引;这真的没有意义。数组必须由整数索引。即一个数组由位置0、位置1、2等的元素组成;说“位置 0.1 的数组元素”并没有多大意义。

    要编译您的代码,您需要在函数“averageOfNumbers”的 for 循环中将变量“i”声明为“int”而不是“double”。

    【讨论】:

      【解决方案4】:

      代码中的修改: 根据您的问题,您要计算包括0在内的所有负数的平均值。

      错误:

      1. 检查数字是否小于 0 的方法。%2 检查数字是否为偶数。
      2. 计算平均值的方法是计算总和和计数,然后将它们除以最小化浮点误差。

        public static double averageOfNumbers(double[] x){
        
        double avg = 0.0;
        double sum = 0.0;
        int count=0; 
        if (x != null){
            for (int i = 0; i < x.length; i++){
                if ( x[i]>=0 ){  
                    sum = sum + x[i];  
                    count=count+1; 
                }
            }
        }
        if(count!=0){
          avg=sum/count;
        }
        return avg;
        }
        

      【讨论】:

        【解决方案5】:

        使用 Java 8 Strems 的简单单行器:

        double avg=Stream.of(x).mapToDouble(d->d).map(num->num<=0).average().orElse(0.0);
        

        它创建一个DoubleStream (mapToDouble) 并删除所有大于 0 的数字并计算平均值。

        如果没有结果(因为x 为空)它将返回0。

        参考this。

        【讨论】:

          猜你喜欢
          • 2017-01-02
          • 1970-01-01
          • 1970-01-01
          • 2022-01-15
          • 1970-01-01
          • 2017-04-18
          • 1970-01-01
          • 1970-01-01
          • 2014-05-14
          相关资源
          最近更新 更多