想法是创建一个静态方法,用于计算部分填充数组的平均工资。假设 numEmployees 保存数组中具有有效数据的元素数量。 numEmployees 被传递给该方法。
public static double getAverage(double[ ] numEmployees)
{
double total = 0;
double average;
for (int i = 0; i < numEmployees.length; i++)
total += numEmployees[i];
average = total / numEmployees.length;
return average;
}
我需要在方法中添加一个部分来计算填充的数组吗? 像:
int count=0;
int p=0;
if (numEmployees[p]>0)
{
count++;
p++;
}
或者我应该在消息内的 for 循环中添加一部分并将总计更改为:
for (int i = 0; i < numEmployees.length || numEmployees>0; i++)
total += numEmployees[i];
比往下更远
average = total / i;
最佳答案
public static double getAverage(double[] numEmployees)
{
double total = 0;
double count = 0;
for (int i = 0; i < numEmployees.length; i++)
if (numEmployees[i] > 0) {
total += numEmployees[i];
count++;
}
return total / count;
}
请注意,如果第一个 0 之后不能再有任何值,则最好在检测到一个值时结束循环。我在这里写的内容查找任何大于 0 的值,无论 0 出现在哪里。
关于java - 求部分填充数组的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7935577/