gpt4 book ai didi

javascript - 我的 if else 语句中的变量数字没有更新

转载 作者:行者123 更新时间:2023-12-01 00:06:34 25 4
gpt4 key购买 nike

我正在尝试运行这个简单的银行“应用程序”,但我无法正确更新值。我尝试通过按“d”作为第一个输入提示 userDesposit,然后按“b”提示 userBalance,但无论我输入什么数字,该值始终会被警告为 0。另外,在我第一次运行时,在提示一些选择后我无法让它退出 - 但如果我按“q”作为我的第一选择,我可以让它立即退出。有人可以帮我解决这些问题吗?谢谢!

function userBank() { 
let userBalance = 0;
let continueBanking = true;
let userInput = prompt ("Enter 'q' to quit immediately, Enter 'w' to withdraw money, Enter 'd' to deposit money, Enter 'b' to view your balance.");

while (continueBanking == true) {
if (userInput == "w") {
let userWithdraw = prompt ("How much would you like to withdraw?");
userBalance = userWithdraw;
userBank();
} else if (userInput == "d") {
let userDeposit = prompt("How much would you like to deposit?");
userBalance = userDeposit;
userBank();
} else if (userInput == "b") {
alert("Here is your current balance: " + userBalance);
userBank();
} else if (userInput == "q") {
alert("Banking app is now closing.");
continueBanking == false;
return;
}
else {
alert("Invalid user input. Try again.");
return;
}
}
}

userBank();

最佳答案

您不应该递归调用该函数。由于 while 循环,它已经重复了。每个递归级别都有自己的 userBalance 变量副本,该副本初始化为 0

递归也使得退出应用程序变得困难。您必须输入 q 次数与它的递归次数相同。

您只需将操作提示移动到循环内,而不用再次调用该函数。

您也不需要添加和减去用户存款和取款的金额,您只需设置余额即可。

function userBank() {
let userBalance = 0;

while (true) {
let userInput = prompt("Enter 'q' to quit immediately, Enter 'w' to withdraw money, Enter 'd' to deposit money, Enter 'b' to view your balance.");
if (userInput == "w") {
let userWithdraw = prompt("How much would you like to withdraw?");
userBalance -= parseFloat(userWithdraw);
} else if (userInput == "d") {
let userDeposit = prompt("How much would you like to deposit?");
userBalance += parseFloat(userDeposit);
} else if (userInput == "b") {
alert("Here is your current balance: " + userBalance);
} else if (userInput == "q") {
alert("Banking app is now closing.");
break;
} else {
alert("Invalid user input. Try again.");
}
}
}

userBank();

关于javascript - 我的 if else 语句中的变量数字没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60330541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com