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