开发者

Javascript check for Max/Min/Average number from a record set

function lab09unknownLoopCountPart2() {

//Constants
var ONE_HUNDRED = 100;
var ZERO = 0;

//Variables
var employeeHourlyWage;
var hourlyMaximum = ZERO;
var hourlyMinimum = ZERO;
var totalHourlyWage = ZERO;
var 开发者_运维技巧records;
var counter = ZERO;
var average;

records = openEmployeePayrollRecords();

while (records.readNextRecord()) {
   employeeHourlyWage  = records.getEmployeeHourlyWage();
   totalHourlyWage += employeeHourlyWage;
   counter++;
   average = totalHourlyWage / counter;

   if (employeeHourlyWage < ONE_HUNDRED) {
       hourlyMaximum = employeeHourlyWage;
   }
   if (employeeHourlyWage < ONE_HUNDRED) {
       hourlyMinimum = employeeHourlyWage;
   }
}
document.write("Average Hourly Wage: " + average + "<br />");
document.write("Maximum Hourly Wage: "  + hourlyMaximum + "<br />");
document.write("Minimum Hourly Wage: " + hourlyMinimum + "<br />");

}

The record set is simply numbers from 15 - 30. I have to sort through them and find the Maximum, Minimum and Average.

I know that my two IF statements are incorrect and I'm wondering how to check this, without using Math.min and Math.max.

Thanks.


   var hourlyMinimum = -1;
   var hourlyMaximum = -1;

   if (hourlyMaximum === -1 || employeeHourlyWage > hourlyMaximum ) {
       hourlyMaximum = employeeHourlyWage;
   }
   if (hourlyMinimum === -1 || employeeHourlyWage < hourlyMinimum ) {
       hourlyMinimum = employeeHourlyWage;
   }

Assuming wages cannot be negative.


if (employeeHourlyWage > hourlyMaximum)
    hourlyMaximum = employeeHourlyWage;
if (employeeHourlyWage < hourlyMinimum)
    hourlyMinimum = employeeHourlyWage;

Also you could move average calculation outside of the loop cuz it's value used only outside.

By the way, what's the point of using those ZERO and ONE_HUNDRED constants - they are not anyhow semantical.


For your two "if conditions" you are checking whether the new value for wage is greater than the maximum or minimum.

Where hourlyMaximum gives the maximum value for each EmployeeHourlyWage in the EmployeePayrollRecords set.

and

hourlyMinimum gives the minimum value for each EmployeeHourlyWage in the EmployeePayrollRecords set.

So for each iteration in the while loop you need to reassign the value of the wage with in the if block.

If the current wage acquired from records is greater than the current maximum then assign it otherwise don't. A similar process for the minimum.

The current "if blocks" just reassigns the value of the hourly minimum and maximum wages once it is lower than 100 (ONE_HUNDRED)

To prove to yourself that you are indeed getting the correct values ,try outputting them by code and by hand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜