简体   繁体   中英

Finding the average in a partially filled array

The Idea is to create a method that is static that will calculate the average salary for a partially-filled array. Assume that numEmployees holds the number of elements in the array that have valid data. numEmployees is passed to the method.

 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;
}

Do I need to add a part in the method that counts the array that are filled? like:

 int count=0;
 int p=0;
 if (numEmployees[p]>0)
 {
 count++;
 p++;
 }

or should I add a part in my for loop inside the message and change my total to this:

for (int i = 0; i < numEmployees.length || numEmployees>0; i++)
 total += numEmployees[i];

Than farther down

 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;
}

Note that if there can be no more values after the first 0, it's also good to end the loop when one is detected. What i wrote here looks for any value greater than 0, no matter where the 0's occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM