我正在努力研究一个程序,以计算将投资翻倍所需的年数(例如100美元),在此示例中为3.5%的利息。利息/投资的价值可以变化。我希望看到每年的结果。我的循环工作,但我需要在金额加倍(200 $)之后停止我的循环,而不是200年之后。你可以帮我修改我的脚本,在金额加倍后停止计算吗?
=============================================== =========================
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var investment = 100;
var rate = 0.035;
var text = "";
for (var i=1; i <= investment * 2; i++) {
text += "total amount in "+i+" years is " + "$" + (investment * ( 1 + (i * rate))) + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
答案 0 :(得分:1)
您可以使用while
循环的不同方法,并通过检查实际资本与双倍投资。
在循环内部,获得感兴趣的资本一年并增加year
计数器。然后将此信息添加到输出中。
var investment = 100,
rate = 0.035,
capital = investment,
year = 0;
while (capital < investment * 2) {
capital += capital * rate;
year++;
document.getElementById("demo").innerHTML += "total amount in " + year + " " + (year === 1 ? "year" : "years") + " is " + "$" + capital.toFixed(2) + "<br>";
}
<p id="demo"></p>
答案 1 :(得分:0)
您需要将for循环条件中的金额与双重市长进行比较,而不是将年份与双重投资进行比较
for (var i=1; (investment * ( 1 + (i * rate))) <= investment * 2; i++) {
text += "total amount in "+i+" years is " + "$" + (investment * ( 1 + (i * rate))) + "<br>";
}