简体   繁体   English

如何从数组中减去数字以使总数为 0。我想跳过会使总数为负数的数字

[英]How can I subtract numbers from an Array to get my total to 0. I want to skip numbers that would make my total a negative

I am not done with this project, but I am stuck in one part of the project.我还没有完成这个项目,但我被困在项目的一部分中。 I am having trouble just pushing the numbers that will make my total 0. For example if the change I need to give back is 5.50 my array should be [5,.50].我在推送使我的总数为 0 的数字时遇到了麻烦。例如,如果我需要返回的更改是 5.50,我的数组应该是 [5,.50]。 My numbers in my Array should not exceed the numbers inside myArr1.我的数组中的数字不应超过 myArr1 中的数字。 I might not be phrasing the question right but any insight on how to tackle this problem would be wonderful.我可能没有正确地表达这个问题,但任何关于如何解决这个问题的见解都会很棒。 Thank you!谢谢!

 function checkCashRegister(price, cash, cid) { let myArr = []; let myChange = 0 let change = cash-price; let total = cash - price let myArr2 = [] let myMon = [["PENNY", .01], ["NICKEL", .05], ["DIME",.1, ],["QUARTER", .25], ["ONE", 1],["FIVE", 5],["TEN", 10],[ "TWENTY", 20],["ONE HUNDRED", 100]] let myArr1 = {"PENNY":1.01, "NICKEL": 2.05,"DIME":3.1,"QUARTER": 4.25, "ONE": 90,"FIVE": 55,"TEN": 20, "TWENTY": 60,"ONE HUNDRED": 100} let myNum = {"PENNY":.01, "NICKEL": .05,"DIME":.1,"QUARTER": .25, "ONE": 1,"FIVE": 5,"TEN": 10, "TWENTY": 20,"ONE HUNDRED": 100} for(let i =0; i <myMon.length; i++){ if(myMon[i][1] <= change){ myArr.unshift(myMon[i][1]) } } for(let i = 0; i<myArr.length; i++){ myArr2.push(total -= myArr[i]) } return myArr2 } console.log(checkCashRegister(70, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]));

Don't work with fractions for currency.不要使用分数作为货币。 Javascript's Number type is binary-based floating point only, which means some decimal fractions aren't exactly represented. Javascript 的Number类型仅是基于二进制的浮点数,这意味着某些小数部分不能精确表示。 See below:见下文:

 //working with fractions of Dollars let change = 6.30 let dime = 0.10 let dimeCoins = change / dime //you won't get exactly 63 dimes console.log(63, dimeCoins, 63 - dimeCoins) //working with cents (no inexact rounding of fractional values) change = 630 dime = 10 dimeCoins = change / dime console.log(63, dimeCoins, 63 - dimeCoins)

As for your problem model, keep in mind that for every currency denomination , the cash register has a number of units with the corresponding individual value .至于您的问题模型,请记住,对于每种货币面额,收银机都有许多具有相应个体价值的单位。

When picking change, the cashier always tries to exhaust the greatest bills before moving on to the lesser, next greatest ones .挑选零钱时,收银员总是试图用尽最大的钞票,然后再转向较小的、次大的钞票。

You can solve this problem using no objects, two arrays and a for loop.您可以不使用对象、两个数组和一个 for 循环来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM