Javascript 查找总计到给定金额数组的最小纸币数和值

Javascript 查找总计到给定金额数组的最小纸币数和值,javascript,arrays,Javascript,Arrays,当我试图得到这个值2316它的返回值[0,2,0,3,0,0,2,1,0,1]但是我需要把它输出[0,2,0,3,0,0,0,1,1,0,1],我认为我的算法有问题 function findNoteAndCoins(salary) { var note = [5000,1000,500,100,50,20,10,5,2,1]; var noteCount = new Array(10); noteCount = Array.from(noteCount, item => it

当我试图得到这个值2316它的返回值[0,2,0,3,0,0,2,1,0,1]但是我需要把它输出[0,2,0,3,0,0,0,1,1,0,1],我认为我的算法有问题

function findNoteAndCoins(salary) {
  var note = [5000,1000,500,100,50,20,10,5,2,1];
  var noteCount = new Array(10);
  noteCount = Array.from(noteCount, item => item || 0);

    for(var i = 0; i < 10; i++){
        if (salary >= note[i]){
            noteCount[i]= salary / note[i];
            salary = salary % note[i];
        }
    }

   for(var j = 0; j < 10; j++){
        if (noteCount[j] != 0){
            var count = noteCount[j];
        }
    }

  return noteCount.map(num => (num * 1).toFixed(0));  
}

findNoteAndCoins(2316);
函数findNoteAndCoins(工资){
var注释=[50001000500100,50,20,10,5,2,1];
var noteCount=新数组(10);
noteCount=Array.from(noteCount,item=>item | | 0);
对于(变量i=0;i<10;i++){
如果(工资>=注[i]){
noteCount[i]=工资/票据[i];
工资=工资百分比注[i];
}
}
对于(var j=0;j<10;j++){
如果(noteCount[j]!=0){
var计数=票据计数[j];
}
}
返回noteCount.map(num=>(num*1.toFixed(0));
}
发现钱币(2316);

要将浮点数转换为整数,请使用
Math.trunc
Math.floor
Math.trunc(剩余/注释)

整个代码可以如下所示:

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
功能是否有效:

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);
函数findSalary(notesCount){
常量注释=[5000,1000,500,100,50,20,10,5,2,1];
工资=0;
for(设i=0;i
(1.6).toFixed(0)=“2”-使用
Math.floor
。如何应用此代码段?
notecont[I]=Math.floor(salary/note[I]),您也可以截断,但这并不重要,因为您的值总是正值。顺便说一句,我完全不理解你的第二个循环,它似乎完全没有意义。