1

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?

1
  • Not really sure what your question is about. Could you elaborate a bit? Commented Nov 22, 2009 at 10:34

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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;

2 Comments

Put it in a do { ... } while(0); to make him happy.
yeah, thinking how to put for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.