views:

92

answers:

2

Suppose a carpark charges a $2 minimum fee to park for up to 3 hours, then the carpark charges an additional $0.5 per hour for each hour. For example, park for 5 hours charge $2+$0.5+$0.5=$3

How should I calculate the fee use for loop?

A: 

May be like this, sorry If it is wrong, coz I didnt test it.

fee=0
if (hour>0){
    fee=2;
    hour-=3;

    //without for loop
    //if(hour>0)fee+=0.5*hour;

    //with for loop
    for(var i=0;i<hour;i++){
        fee+=0.5;
    }

}
return fee;
S.Mark
Put it in a do { ... } while(0); to make him happy.
Alex
yeah, thinking how to put for loop
S.Mark
never mind, good for reference
Programme Newbie
+4  A: 

There's no need to use a for loop:

function calculateFee(hours) {
    if (isNaN(hours) || hours <= 0) return 0;
    if (hours <= 3) return 2;
    var additionalHours = Math.round(hours - 3);
    return 2 + 0.5 * additionalHours;
}

var fee = calculateFee(5);

And if using a for loop is a requirement:

function calculateFee(hours) {
    if (isNaN(hours) || hours <= 0) return 0;
    var result = 2;
    if (hours <= 3) return result;
    var additionalHours = Math.round(hours - 3);
    for (i = 0; i < additionalHours; i++) {
        result += 0.5;    
    }
    return result;
}

And finally an example using objects:

function FeeCalculator(minimalFee, initialHours, additionalHourFee) {
    if (isNaN(minimalFee) || minimalFee <= 0) { throw "minimalFee is invalid"; }
    if (isNaN(initialHours) || initialHours <= 0) { throw "initialHours is invalid"; }
    if (isNaN(additionalHourFee) || additionalHourFee <= 0) { throw "additionalHourFee is invalid"; }
    this.minimalFee = minimalFee;
    this.initialHours = initialHours;
    this.additionalHourFee = additionalHourFee;
}

FeeCalculator.prototype = {
    calculateFee: function(hours) {
        if (hours <= this.initialHours) return this.minimalFee;
        var additionalHours = Math.round(hours - this.initialHours);
        return this.minimalFee + this.additionalHourFee * additionalHours;    
    }
};

var calculator = new FeeCalculator(2, 3, 0.5);
var fee = calculator.calculateFee(5);
Darin Dimitrov