出于某种原因,我在使用循环工作时遇到困难。每当我尝试测试它时,它一直会崩溃我的浏览器,在一个案例中,我能够在控制台中看到循环的结果,我所看到的只是NaN打印了好几次。我的代码中有没有遗忘的东西?
<div id="output"></div>
<script>
var starting = prompt("What is your starting balance?");
var target = prompt("What is your target balance?");
var interest = prompt("What is your interest rate?");
var periods = 0;
var current = starting;
var greaterThan = false;
while (greaterThan === false) {
if (current < target) {
current = current + (current * interest);
periods++;
} else {
greaterThan = true;
alert("it took " + periods + " periods to make your starting balance greater than your target balance.");
document.querySelector('#output').textContent = "to grow an initial investment of " + starting + " to " + target + " at a " + interest + " interest rate will require " + periods + " investment periods.";
}
}
</script>
答案 0 :(得分:6)
我能看到的一个问题是,你的所有输入值都是字符串,而不是数字,所以他们正在进行字符串比较而不是数字
var starting = +prompt("What is your starting balance?") ||0;
var target = +prompt("What is your target balance?")||0;
var interest = +prompt("What is your interest rate?")||1;
+
前面的prompt()
是unary plus运算符
答案 1 :(得分:4)
您忘记将提示中的结果从字符串转换为数字。
var starting = parseFloat(prompt("What is your starting balance?"));
对用户从提示输入的其他数字执行相同的操作。
答案 2 :(得分:0)
首先,您需要将输入转换为整数值。提示输入是一个字符串。即使你输入1或10或任何数字。你可以使用parseInt()。而且因为你要求利率,我认为任何用户都会输入类似2.5或10的百分比。不是0.1或0.05。即使他这样做,parseInt()函数也不能正确,因为0.05不是整数值。你可以使用parseFloat。所以我建议你看下面我的代码实现。另外,我省略了if else语句,因为它们不是必需的,只会使代码更复杂。
<div id="output"></div>
<script type="text/javascript">
var starting = parseInt(prompt("What is your starting balance?"));
var target = parseInt(prompt("What is your target balance?"));
var interest = parseInt(prompt("What is your interest rate?"));
var periods = 0;
var intrate = interest/100;
var current = starting;
while (current< target) {
current += (current*intrate);
periods += 1;
}
alert("it took " + periods + " periods to make your starting balance greater than your target balance.");
document.querySelector('#output').textContent = "to grow an initial investment of " + starting + " to " + target + " at a " + interest + " interest rate will require " + periods + " investment periods.";
</script>