簡體   English   中英

在部分填充的數組中查找平均值

[英]Finding the average in a partially filled array

這個想法是創建一個靜態的方法,該方法將計算部分填充數組的平均薪水。 假設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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM