不知道如何解决这个练习

时间:2019-04-16 15:12:28

标签: javascript arrays function for-loop

我必须以法定货币计算确切的汇率。确切的纸币和硬币必须插入阵列中。我陷入了这一步,不知道如何解决。

function countChange(amount) {
    const currency = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
    const change = [];

    for (let i = 0; i < currency.length; i++) {
        const value = currency[i];
        if (value <= amount) {
            change.push(value)
        }

    }
    return change;

};


console.log(countChange(500.26));

2 个答案:

答案 0 :(得分:1)

下面是一个简单的示例。

只需简单地迭代每种造币大小,只需将当前总数除以每种造币大小即可,如果有任何造币,则将其推入数组。

function countChange(amount) {
    const currency = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
    const change = [];
    for (let i = 0; i < currency.length; i++) {
        const coinsize = currency[i];
        //how many coins?
        const coins = Math.trunc(amount / coinsize);
        //remove these from total
        amount -= coinsize * coins;
        //fix rounding problems.
        amount = Math.round(amount * 100) / 100;
        //add to our result
        if (coins > 0)
        {
            change.push({
                coinsize,
                coins
            });
        }
    }
    return change;
};


console.log(countChange(500.26));

答案 1 :(得分:0)

我认为这可能是您所期望的:

function countChange(amount) {
    const currency = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
    const change = [];
    var changed = 0;
    while(changed < amount){
        for(var i = 0; i < currency.length; i++){
            if(amount-currency[i] >= 0){
                change.push(currency[i]);
                changed+=currency[i];
                amount-=currency[i];
            }
        }
    }
    return change;

}

console.log(countChange(500.26))