Javascript 自动售货机不退零钱
这是一个代码: 在这里,我试图模拟自动售货机。到目前为止,如果插入的信用卡不够,我可以退还硬币,我可以让机器告诉我需要多少零钱,但我无法让它退还零钱 根据自动售货机拥有的硬币,零钱应作为物品返还Javascript 自动售货机不退零钱,javascript,javascript-objects,Javascript,Javascript Objects,这是一个代码: 在这里,我试图模拟自动售货机。到目前为止,如果插入的信用卡不够,我可以退还硬币,我可以让机器告诉我需要多少零钱,但我无法让它退还零钱 根据自动售货机拥有的硬币,零钱应作为物品返还 //if this.coins = {1:1, 2:0, 4:3, 6:2} //and the change needed is 8 //the change should be changeObj = {1: 1, 6: 1} //the machine is sneaky and can retu
//if this.coins = {1:1, 2:0, 4:3, 6:2}
//and the change needed is 8
//the change should be changeObj = {1: 1, 6: 1}
//the machine is sneaky and can return less than the required amount, but not more.
这里,用于计算更改并返回更改对象的循环按预期工作
vmCoins={1:1,2:0,4:3,6:2}
设changeObj={}
让change=8
for(设d=changeNeeded;d>0;d--){
而(vmCoins[d]>0&&(ChangeRequired-d)>=0){
changeObj[d]?changeObj[d]+:changeObj[d]=1
货币发行量[d]--
需要更改-=d
}
}
log(changeObj)
我认为问题在于循环本身的条件。
事实上,你有:
for (let d=changeNeeded; d<0; d--){
我希望这足够了。在工作版本中,您有
d>0
,但在非工作版本中,您将其更改为d<0
。这是故意的吗?唉,这是个错误。现在工作。。。
for (let d = changeNeeded; d > 0; d--){