1 回答

TA貢獻1784條經(jīng)驗 獲得超9個贊
要將音符的浮點數(shù)轉(zhuǎn)換為整數(shù),請使用Math.trunc或Math.floor:Math.trunc(remaining / note)
整個代碼看起來像:
function findNoteAndCoins(salary) {
const notes = [5000, 1000, 500, 100, 50, 20, 10, 5, 2, 1];
const notesCount = [];
let remaining = salary;
for (const note of notes) {
if (salary >= note) {
notesCount.push(Math.trunc(remaining / note));
remaining = remaining % note;
} else {
notesCount.push(0);
}
}
return notesCount;
}
console.log(findNoteAndCoins(2316));
我們可以檢查該findNoteAndCoins函數(shù)是否有效:
function findSalary(notesCount) {
const notes = [5000, 1000, 500, 100, 50, 20, 10, 5, 2, 1];
let salary = 0;
for (let i = 0; i < notesCount.length; i++) {
salary += notesCount[i] * notes[i];
}
return salary;
}
console.log(findSalary(findNoteAndCoins(2316)) === 2316);
添加回答
舉報