该功能应显示与某个值对应的硬币数量;即:56的输入应显示回[25,25,5,1]。
我遇到了麻烦: 1)在阵列中显示2+相同的硬币(我理解下面的数学函数没有正确使用) 2)从数组中删除任何0
感谢您的帮助。
function getCoins(){
let coins = [25, 10, 5, 1];
amount = prompt ("Enter an amount to convert into coins");
coinAmount = "";
for (i = 0; i < coins.length; i++){
if (amount % coins[i] >= 0){
coinAmount += coins[i] * (Math.floor (amount/coins[i])) + ",";
amount = amount % coins[i];
console.log (coinAmount)
}
}
}
getCoins()
&#13;
答案 0 :(得分:1)
一个选项是push
数组并使用join
来显示它。
您可以使用硬币类型将concat
硬币安装到new Array(NumberOfCouns)
和fill
。
function getCoins() {
let coins = [25, 10, 5, 1];
let amount = prompt("Enter an amount to convert into coins");
let coinAmount = [];
for (i = 0; i < coins.length; i++) {
if (Math.floor(amount / coins[i]) > 0) {
coinAmount = coinAmount.concat(new Array(Math.floor(amount / coins[i])).fill(coins[i]));
amount = amount - (Math.floor(amount / coins[i]) * coins[i]);
}
}
console.log(coinAmount.join())
}
getCoins();
答案 1 :(得分:0)
这个怎么样?
function getCoins(){
let coins = [25, 10, 5, 1];
amount = prompt ("Enter an amount to convert into coins");
coinAmount = "";
for (i = 0; i < coins.length; i++){
if (amount >= coins[i]){
var integer = parseInt(amount/coins[i]);
coinAmount += integer + ",";
amount -= integer*coins[i];
console.log (coinAmount);
}
else{
coinAmount += "0,";
console.log (coinAmount);
}
}
}
getCoins()
输入30:
1,
1,0,
1,0,1,
1,0,1,0,
因为我们有1个值为25的硬币和1个值为5的硬币
输入25:
1,
1,0,
1,0,0,
1,0,0,0,