我還是一個初學者,在這裏總共noob,所以請耐心等待,我來到這個練習基本上是分散到25,10,5,2,1足夠數量的硬幣/美分的金額。如何在JavaScript中僅使用條件語句來編寫硬幣計數器函數?
因爲我還在學習,所以不熟悉內置函數,我試圖只寫條件語句。
功能與所測試的數目65效果很好,得到的25的陣列,25%,10%,5分別
然而,當我用數字46測試時,它給了25的陣列,25個,10 ,5,25,10,10,1這顯然是錯誤的,而且我的功能顯然是錯誤的。
請您將錯誤指向我。
這裏是我的代碼,並提前感謝。
var co = [];
function coin(n){ //46
// co = [25,]
if (n>=25){
co.push("25");
n = n-25;
coin(n);
}
else if (n>=10){
co.push("10");
n = n-10;
coin(n);
}
else if (n>=5){
co.push("5");
n = n -5;
coin(n);
}
else if (n>=2){
co.push("2");
n = n - 2;
coin(n);
}
else if (n>=1){
co.push("1");
n = n - 1;
coin(n);
}
else if (n == 0){console.log(co);}
}
你沒有遞歸的第二種解決方案是輝煌的。謝謝 請問爲什麼你需要重新分配co作爲函數中的空數組? –
因爲它是一個全局變量,這意味着每次調用函數時它都不會被清除。相反,它會將新的解決方案添加到舊的解決方案中。如果我沒有重新分配它,那麼發生在你身上的問題將再次發生;從先前調用該函數存儲的數字將保留在「co」數組中。 –
如果你不需要'co'成爲一個全局變量,你可以在第二個函數中聲明它,而不用重新分配它。 –