简体   繁体   中英

Can't quite get two variables to add and subtract properly. (Javascript)

Currently I'm trying to use prompts to assign an integer to variables, and then add/subtract based on if the input is a negative or positive value, currently it will add, but it won't subtract.

var creditLimit = parseInt(prompt("What is your credit limit?"))
var initialBalance = parseInt(prompt("What is your current balance?"))
var balanceChange = parseInt(prompt("Please enter a charge or a credit amount"))
var newBalance 

if (balanceChange > 0) {
    newBalance = initialBalance + balanceChange;
} else if (balanceChange < 0) {
    newBalance = initialBalance - balanceChange;
} else {
    alert("Please enter a valid integer")
}

I know the alert could probably be something better, but right now I'm just breaking down a credit balance calculator and got held up at this spot.

else if (balanceChange < 0) {
    newBalance = initialBalance - balanceChange;
}

The balanceChange < 0 ie it will be a negative value, so initialBalance - (- balanceChange) = initialBalance + balanceChange

that causing the problem here.

Ah, I just figured it out, I suppose I was trying to use a double negative operation by subtracting a negative input!

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