简体   繁体   中英

How to make sure my while loop does not break my condition?

I'm practicing a simple while loop. Buy a phone for the cost of 200 only until my bank account hits 500, but because it buys the phone first it only knows you dropped below 500 after it buys the phone.

In my code, it's buying until it takes the bankaccountmoney variable to 400:

 var bankaccountmoney = 2000; var phonesbought = 0; var phonecost = 200; while (bankaccountmoney > 500) { phonesbought = phonesbought + 1; bankaccountmoney = bankaccountmoney - phonecost; console.log("money: " + bankaccountmoney + " phonesbought: " + phonesbought); } 

while (bankaccountmoney - phonecost >= 500) {
...
}

Another approach, using a couple of utility functions. I don't like doing math in while predicates. Way too easy to misread.

 const phoneCost = 200; const targetSavings = 500; // Can I afford to buy something, given target savings, purchase price, // and current funds? const canAffordPurchase = target => purchase => funds => (funds - purchase >= target); // Can I afford to buy this phone in particular? const canAffordPhone = canAffordPurchase(targetSavings)(phoneCost); let availableFunds = 2000; let phonesBought = 0; // Buy as many phones as I can afford. while(canAffordPhone(availableFunds)) { phonesBought += 1; availableFunds -= phoneCost; console.log(`money: ` + availableFunds + " phonesBought: " + phonesBought); } 

 var bankaccountmoney = 2000; var phonesbought = 0; var phonecost = 200; while (bankaccountmoney >= (500 + phonecost)) { phonesbought++; bankaccountmoney -= phonecost; console.log("money left: " + bankaccountmoney + " phonesbought: " + phonesbought); } 

and here's a snippet if you instead have 100 as phone cost

 var bankaccountmoney = 2000; var phonesbought = 0; var phonecost = 100; while (bankaccountmoney >= (500 + phonecost)) { phonesbought++; bankaccountmoney -= phonecost; console.log("money left: " + bankaccountmoney + " phonesbought: " + phonesbought); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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