[英]Average of non-zero values in array (Java)
I'm trying to find the average of an array but I only want the values greater than zero to be included. 我试图找到一个数组的平均值,但我只想包含大于零的值。 This is what I have right now: 这就是我现在所拥有的:
double total = 0;
double average;
for (int index = 1; index < monthlyVisitors.length; index++)
{
if (monthlyVisitors[index] > 0)
total += monthlyVisitors[index];
}
average = total / monthlyVisitors.length;
I've tried what feels like a million different things at this point. 在这一点上,我已经尝试了100万种不同的感觉。 I know it's simple but I can't figure it out. 我知道这很简单,但我无法弄清楚。 Thanks! 谢谢!
Add a counter to the if
block and then divide total
by the count
. 在if
块上添加一个计数器,然后将total
除以count
。
Also, you're starting at index 1, which you probably don't want to do since arrays are 0-indexed (they start at 0 instead of 1). 另外,您从索引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;
You can use an advanced for loop
to iterate the monthlyVisitors
. 您可以使用高级的for loop
来迭代monthlyVisitors
。
It gets rid of the need for int index
它摆脱了对int index
int total = 0;
int nonzeroMonths = 0;
for(int visitors : monthlyVisitors)
if(visitors > 0)
{
total += visitors;
nonzeroMonths++;
}
double average = ( (double) total / nonzeroMonths );
Or you can get rid of the months with 0 visits and use a lambda (Java 1.8) to sum the list, divide by the size 或者,您也可以使用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();
Create another variable (a counter) which is incremented by one when you found a non zero value. 创建另一个变量(计数器),当发现非零值时该变量将增加一。 Then divide the total with this variable. 然后将总数除以该变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.