专注于for循环。我希望有兴趣建立最新的价值变量。当这个脚本运行时,我得到的是每年相同的利率和相同的价值。我希望它使用最后一个值变量来计算每年的新值。以下是程序在浏览器中的显示方式: 年份:1 兴趣:750 价值:10750
年份:2 兴趣:750 价值:10750
年份:3 兴趣:750 价值:10750
年份:4 兴趣:750 价值:10750
年份:5 兴趣:750 价值:10750
投资金额= 10000利率= 7.5年= 5期货价值为10750
感谢您使用Future Value应用程序。值和兴趣应该增加。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Future Value Application</title>
<script>
var futureValue;
var investment = prompt("Enter investment amount as xxxxx.xx", 10000);
investment = parseFloat(investment);
var rate = prompt("Enter interest rate as xx.x", 7.5);
rate = parseFloat(rate);
var years = prompt("Enter number of years", 10);
years = parseInt(years);
// calulate future value
futureValue = investment;
for (var i = 1; i <= years; i++ ) {
var cInterest;
var value;
document.write("Year: " +(i) + "<br>");
cInterest = futureValue * rate / 100;
cInterest = parseInt(cInterest);
document.write("Interest: " + cInterest + "<br>");
value = futureValue + cInterest;
value = parseInt(value);
document.write ("Value: " + value + "<br><br>");
cInterest += value;
}
futureValue = parseInt(futureValue);
</script>
</head>
<body>
<main>
<script>
document.write("Investment amount = " + investment);
document.write(" Interest rate = " + rate);
document.write(" Years = " + years);
document.write(" Future Value is " + (futureValue + futureValue* rate / 100) + "<br><br>");
</script>
Thanks for using the Future Value application.
</main>
答案 0 :(得分:0)
考虑看看这个: https://msdn.microsoft.com/library/bzt2dkta(v=vs.94).aspx
正如alexei在他的评论中提到的,你的值和cInterest变量都在for循环中声明。这些变量的值只能通过它们所在的范围持续。在这种情况下,这两个变量都在for循环中。因此,在每次迭代之后,它们将被重新初始化。
我不确定你特别想要发生什么,但你可以做到:
var cInterest;
var value; //not sure what you want to do with this.
for (var i = 1; i <= years; i++ ) {
document.write("Year: " +(i) + "<br>");
cInterest = futureValue * rate / 100;
cInterest = parseInt(cInterest);
document.write("Interest: " + cInterest + "<br>");
value = futureValue + cInterest; //value is getting 'reset' here.
value = parseInt(value);
document.write ("Value: " + value + "<br><br>");
cInterest += value;
}
futureValue = parseInt(futureValue);
您的cInterest应该用这个正确计算。但是,我不确定您计划对值变量做什么。