如何计算数组中仅包括输入值的平均值

huangapple go评论63阅读模式
英文:

How to calculate average of an array for only entered values

问题

我尝试计算数组中非零值的平均值。我的数组大小为15,因为它最多可以有15个值。

当我计算平均值时,它使用了所有15个值,即使其中12个在开始时为0。如何防止考虑0.0的值?

for(double element: majorA) {
       Sum += element;
}
average = sum / majorA.length;
System.out.printf("%.5f\n", average);

此外,数组并不是一个定义好的集合,而是依赖于用户的输入。初始数组为:

double[] majorA = new double[15];

然后根据需要获取值:

majorA[0] = num1;
majorA[1] = num2;
...
英文:

I'm trying to calculate the average of an array for only the values that aren't 0. My array is of size 15, because it could have up to 15 values in it.

When I calculate the average, it uses all 15 values, even though 12 of them are 0 at the start. How do I prevent 0.0’s from being considered?

for(double element: majorA) {
       Sum += element;
}
average = sum / majorA.length;
System.out.printf("%.5f\n", average);

The array also isn't a defined set, but dependent on what the user inputs. The initial array is:

double[] majorA = new double[15];

Then gets values as need:

majorA[0] = num1;
majorA[1] = num2;
...

答案1

得分: 2

我会添加一个计数器来跟踪,并使用它来代替数组长度。

int count = 0;
for (double element : majorA) {
    if (element > 0.0) {
        Sum += element;
        count += 1;
    }
}
average = sum / count;
System.out.printf("%.5f\n", average);
英文:

I would just add a counter that keeps track and use that instead of the array length.

int count = 0;
for(double element: majorA) {
   if(element > 0.0) {
       Sum += element;
       count += 1;
   }
}
average = sum / count;
System.out.printf("%.5f\n", average);

答案2

得分: 1

你可以使用以下一行代码完成:

Arrays.stream(majorA).filter(d -> d != 0).average().orElse(0)

这将过滤掉所有值为0的元素,并计算平均值。即使数组中没有剩余元素,由于使用了 .orElse(0),它也会显示0。

英文:

You can do it in one line with

Arrays.stream(majorA).filter(d -> d != 0).average().orElse(0)

this will filter out all values that are 0s and will calculate the average. Even if there is nothing left in the array will display 0 because of .orElse(0)

答案3

得分: 0

你可以在循环中使用一个计数器,只有在数字不等于0时递增。

int count = 0;
for(double element: majorA) {
   if(element != 0.0){
       sum += element;
       count++;
   }
}
average = (count == 0) ? 0 : sum / count;
英文:

you can use a counter in the loop that increments only if the number !=0

int count = 0;
for(double element: majorA) {
   if(element != 0.0){
       sum += element;
       count++;
   }
}
average = (count == 0) ? 0 : sum / count;

huangapple
  • 本文由 发表于 2020年10月6日 22:54:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64228382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定