找到平均值

时间:2013-09-26 20:31:03

标签: java

我遇到了这个问题,我需要找到HourlyEmp的总薪水平均值, 我有一个超级Employee和两个潜艇HourlyEmpOverTimeEmp 我将Array Emp [命名为。 Employee Emp[] = new Employee[7]< 7项

现在我需要的是..如果我有一个以上的员工在hourlyEmp 如何获得他们的工资平均值? 到目前为止,我有两个想法,但不是以某种方式工作

1

'for(int i=0;i<Emp.length;i++) {
      if (Emp[i] instanceof HourlyEmp)

  System.err.println("Average="+(Emp[i].totalsal()/i));'

2

double avg=0;
  for(int i=0;i<Emp.length;i++) {
      if (Emp[i] instanceof HourlyEmp)
        avg+=Emp[i].totalsal()/i;
  System.out.println("Average="+avg);

我很感激你的帮助:)。

3 个答案:

答案 0 :(得分:2)

如果您正确计算平均值,选项2将起作用。即。

a = Get summation of total salary
b = Get a count of how many instances where HourlyEmp
average = a/b

答案 1 :(得分:2)

由于您只需要HourlyEmp的平均值,因此需要跟踪其中有多少:

double avg=0;
int numHourlies = 0; //number of hourlyEmps you have found so far

for(int i=0; i < Emp.length; i++) 
{
      if (Emp[i] instanceof HourlyEmp)
      {
          //just add up all the values for now ...
          avg += Emp[i].totalsal(); 

          //we have found another HourlyEmp, so we increase our count
          numHourlies ++;
      }
}

// ... and calculate the average by dividing the sum by the number of values
avg /= numHourlies; 

System.out.println("Average="+avg);

答案 2 :(得分:1)

  public double getAverageSalary 
  {
     double totalSalary = 0;
     double hourlyEmps = 0;
     for(int i=0;i<Emp.length;i++)          
     {
          if (Emp[i] instanceof HourlyEmp)
          {
               totalSalary += Emp[i].salary;
               hourlyEmps++;
          }
     }
     return (totalSalary/ hourlyEmps);
  }

然后在print语句中调用此方法。