简体   繁体   English

Javascript-如何计算循环使用的结果?

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

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. 假设停车场在3个小时内的停车费用最低为2美元,那么该停车场每小时收费为0.5美元。 For example, park for 5 hours charge $2+$0.5+$0.5=$3 例如,停车5小时收费$ 2 + $ 0.5 + $ 0.5 = $ 3

How should I calculate the fee use for loop? 我应该如何计算循环使用费?

There's no need to use a for loop: 无需使用for循环:

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: 并且如果需要使用for循环:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM