简体   繁体   English

为什么“if else 语句”不能正常工作?

[英]Why the “if else statement” is not working properly?

I am doing JS Algorithms and Data structures projects in freecodecamp and I am stuck at the last problem "Cash register".我在 freecodecamp 中做 JS 算法和数据结构项目,我被最后一个问题“收银机”困住了。 I already did some of the coding and my code doesn't pass all the tests.我已经进行了一些编码,但我的代码没有通过所有测试。

The link to the problem: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register问题的链接: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register

My code doesn't pass the 3 and 5 number test.我的代码没有通过 3 和 5 数字测试。 In number 3, the output is almost the same, but the last part ["PENNY",0.03], which doesn't match with the output. 3号中,output几乎相同,但最后一部分["PENNY",0.03]与output不匹配。 In number 5, the totalCid and cashback variables are equal but it doesn't return "CLOSED".在数字 5 中, totalCidcashback变量相等,但它不返回“CLOSED”。 If those are equal it should return the status "CLOSED".如果它们相等,它应该返回状态“CLOSED”。

 function checkCashRegister(price, cash, cid) { var cashback = (cash - price) var returnMoney = { status: "", change: [] } var totalCid = cid.map(v => { return v[1] }).reduce((a, b) => { return a + b }).toFixed(2) console.log(cashback) console.log(totalCid) if (totalCid === cashback) { returnMoney.status = "CLOSED" returnMoney.change = cid return returnMoney } else if (totalCid < cashback) { returnMoney.status = "INSUFFICIENT_FUND" returnMoney.change = [] return returnMoney } else { var denomValue = [{ bill: "ONE HUNDRED", val: 100 }, { bill: "TWENTY", val: 20 }, { bill: "TEN", val: 10 }, { bill: "FIVE", val: 5 }, { bill: "ONE", val: 1 }, { bill: "QUARTER", val: 0.25 }, { bill: "DIME", val: 0.10 }, { bill: "NICKEL", val: 0.05 }, { bill: "PENNY", val: 0.01 } ] var newCidArray = []; var currVal = 0; for (let i = 0; i < denomValue.length; i++) { while (cashback >= denomValue[i].val && currVal < cid[8 - i][1]) { cashback -= denomValue[i].val.toFixed(2); currVal += denomValue[i].val; } if (currVal > 0) { newCidArray.push([denomValue[i].bill, currVal]); } currVal = 0; // reset current value (currVal) to zero after the loop has completed } returnMoney.status = "OPEN" returnMoney.change = newCidArray return returnMoney } } console.log(checkCashRegister(19.5, 20, [ ["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0] ]))

You had a total of 3 problems in your code.您的代码中共有 3 个问题。

The first has been pointed out by @trincot: toFixed() returns a string, which you cannot compare with === to a number. @trincot 指出了第一个: toFixed()返回一个字符串,您无法将其与===与数字进行比较。

The second is that even if the cash in the drawer is more than the expected change, you can be in an INSUFFICIENT_FUNDS situation because you cannot split the bills (notes, in British English) and coins you have.第二个是即使抽屉里的现金多于预期的零钱,您也可能处于INSUFFICIENT_FUNDS的情况,因为您无法拆分您拥有的钞票(纸币,用英式英语)和硬币。 This means that at the end of your algorithm you must check whether the change sums up.这意味着在算法结束时,您必须检查更改是否相加。

The third, and major one, comes from working with floating point numbers.第三个,也是主要的一个,来自使用浮点数。 If you click on "Run code snippet under your code" you can see that the change would be 0.49000000000000027 dollars in pennies.如果您单击“在您的代码下运行代码片段”,您可以看到更改为0.49000000000000027美元便士。

The only safe way out of the swamp of floating point is to convert everything to integers.摆脱浮点沼泽的唯一安全方法是将所有内容转换为整数。 So what I did, apart from fixing the first two problems, is convert dollars to pennies in your script.因此,除了解决前两个问题之外,我所做的就是在脚本中将美元转换为便士。 I tried not to alter your script too much, nonetheless.尽管如此,我还是尽量不要过多地改变你的脚本。

function checkCashRegister(price, cash, cid) {
  // P stands for pennies
  var cidP = cid.map(v => [v[0], Math.round(v[1] * 100)])
  var priceP = Math.round(price * 100)
  var cashP  = Math.round(cash * 100)
  var cashbackP = (cashP - priceP)
  var returnMoney = {
    status: "",
    change: []
  }
  var totalCidP = cidP.map(v => {
      return v[1]
    })
    .reduce((a, b) => {
      return a + b
    })
  if (totalCidP === cashbackP) {
    returnMoney.status = "CLOSED"
    returnMoney.change = cid
    return returnMoney
  } else if (totalCidP < cashbackP) {
    returnMoney.status = "INSUFFICIENT_FUNDS"
    returnMoney.change = []
    return returnMoney
  } else {
    var denomValueP = [
      {bill: "ONE HUNDRED", val: 10000},
      {bill: "TWENTY", val: 2000},
      {bill: "TEN", val: 1000},
      {bill: "FIVE", val: 500},
      {bill: "ONE", val: 100},
      {bill: "QUARTER", val: 25},
      {bill: "DIME", val: 10},
      {bill: "NICKEL", val: 5},
      {bill: "PENNY", val: 1}
    ]
    var changeArray = [];
    for (let i = 0; i < denomValueP.length; i++) {
      var currValP = 0;
      while (cashbackP >= denomValueP[i].val && currValP < cidP[8 - i][1]) {
        cashbackP -= denomValueP[i].val;
        currValP  += denomValueP[i].val;
      }
      if (currValP > 0) {
        changeArray.push([denomValueP[i].bill, currValP / 100]);
      }
    }
    if (cashbackP === 0) {
      returnMoney.status = "OPEN"
      returnMoney.change = changeArray
    } else {
      returnMoney.status = "INSUFFICIENT_FUNDS"
      returnMoney.change = []
    }
    return returnMoney
  }
}

As to why those Math.round() are needed, try this:至于为什么需要那些Math.round() ,试试这个:

4567.89 * 100 === 456789  // => false

EDIT编辑

You asked for clarification about the last if-else in the code.您要求澄清代码中的最后一个 if-else。 The fourth paragraph in freecodecamp says: freecodecamp的第四段说:

Return {status: "INSUFFICIENT_FUNDS", change: []} if cash-in-drawer is less than the change due, or if you cannot return the exact change .返回{status: "INSUFFICIENT_FUNDS", change: []}如果现金抽屉少于应找的零钱,或者如果您不能退回确切的零钱

If you got to the end of the algorithm and cashbackP , which you have been decreasing for every bill or coin you added to the change, has not gone to zero, this means that the change is not complete, and you are in the situation I emphasized.如果您到了算法的末尾,并且cashbackP (对于您添加到找零中的每张纸币或硬币,您一直在减少)并没有变为零,这意味着找零不完整,并且您处于我的情况强调。

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

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