gpt4 book ai didi

Javascript 循环 - 在 while 条件中添加一个 var?

转载 作者:行者123 更新时间:2023-11-30 20:00:22 25 4
gpt4 key购买 nike

基本上,我想根据每个月的捐款来计算并显示达到某个点(储蓄余额)所需的月数。

这是我目前所拥有的:

function howLong(initial,interest,goal,added){
var initialDeposit = parseInt(initial);
var interestInt = parseInt(interest);
var targetSaving = parseInt(goal);
var contribution = parseInt(added);
var monthCount = 0;
while(initialDeposit <= targetSaving){
monthCount++;
initialDeposit+contribution
}
alert(monthCount)
}

这是我的 html 表单:

<form>
Initial Deposit:<br />
<input type="number" id="initial"><br /><br />
Interest:<br />
<input type="number" id="interest"><br /><br />
Target savings amount:<br />
<input type="number" id="goal"><br /><br />
Monthly Contribution:<br />
<input type="number" id="contribution"><br /><br />
<input type="button" value="How Long!?" onclick="howLong(document.getElementById('initial').value,document.getElementById('interest').value,document.getElementById('goal').value),document.getElementById('contribution').value">
</form>

最佳答案

您需要将contribution的值添加到initialDeposit

initialDeposit += contribution;

另外一个问题,你的函数调用有错误

document.getElementById('goal').value),document.getElementById('contribution').value"
^ >>>>>>>>>>>>>>>> should go >>>>>>>>>>>>>>>>> ^

应该是

onclick="howLong(
document.getElementById('initial').value,
document.getElementById('interest').value,
document.getElementById('goal').value,
document.getElementById('contribution').value
)"

最后一轮括号提前结束。

function howLong(initial, interest, goal, added) {
var initialDeposit = parseInt(initial);
var interestInt = parseInt(interest);
var targetSaving = parseInt(goal);
var contribution = parseInt(added);
var monthCount = 0;
while (initialDeposit <= targetSaving) {
monthCount++;
initialDeposit += contribution;
}
alert(monthCount)
}
<form>
Initial Deposit:<br />
<input type="number" id="initial"><br /><br /> Interest:
<br />
<input type="number" id="interest"><br /><br /> Target savings amount:<br />
<input type="number" id="goal"><br /><br /> Monthly Contribution:<br />
<input type="number" id="contribution"><br /><br />
<input type="button" value="How Long!?" onclick="howLong(document.getElementById('initial').value,document.getElementById('interest').value,document.getElementById('goal').value,document.getElementById('contribution').value)">
</form>

关于Javascript 循环 - 在 while 条件中添加一个 var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53446500/

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