硬币改变算法问题 - 不工作

Coins changing algorithm problem - not working

我正在使用以下算法来解决换币问题:

for (let coin of coins){
    if(change >= coin){
        if (Math.floor(change/coin) > 0){
            console.log(Math.floor(change/coin)+ " pièces de " + coin + " euro");
            let newChange = change - coin;
            change = newChange;
        }
    }
 }

结果应如下所示:

Purchase of €1.34 paid for with €5:
Change: €3.66 
Coins returned:
2 euro: 1 
1 euro: 1
50 cents: 1 
10 cents: 1 
5 cents: 1 
1 cent: 1

我的结果是这样的:

Purchase of .34 paid for with 
Change: 3.66
1 pièces de 2 euro
1 pièces de 1 euro
1 pièces de 0.5 euro
1 pièces de 0.1 euro
1 pièces de 0.05 euro
1 pièces de 0.01 euro

请注意,您的行:let newChange = change - coin; 是错误的,因为它假设只给出了 1 个硬币,而忽略了多个硬币的情况。

更改 var 的新赋值应该是减少硬币后更改的模数,因此将您的 if 更改为:

if (Math.floor(change/coin) > 0){
    console.log(Math.floor(change/coin)+ " pièces de " + coin + " euro");
    change  = change % coin;
}