开发者

Javascript - How should I calculate the result use for loop?

Su开发者_StackOverflow社区ppose 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?


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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜