0

我正在尝试制作一个 javascript 贷款计算器程序。我似乎无法让我的循环在每一行上放置不同的数字。假设显示从 24 个月、36 个月、48 个月和 60 个月开始还清的金额。我正在使用一个函数来进行计算,但我总是得到 24 个月的结果。我知道您必须将 nummonths 更改为 36、48 和 60,但我不知道该怎么做。我认为循环每次循环都会增加 12 个月。另外,您将如何将数字格式化为货币?最后我得到一个很长的数字。我尝试在 calculate() 上执行 parseFloat,但出现错误。这是我的代码:

<html>
<BODY BGCOLOR="#FFC0CB">
<head>
<title>Chapter 6 Assignment 2</title>
</head>
<body>
<h1>Loan Calculator</h1>

<script type="text/javascript">
var vehicleprice = window.prompt("What is the vehicle price?", "");
var downpayment = window.prompt("What is the amount of the down payment?", "");
var annualinterest = window.prompt("What is the annual interest rate for the loan?", "");
var nummonths = 24
var loanamount = vehicleprice - downpayment
var monthlyinterest = annualinterest / 1200

vehicleprice = parseFloat(vehicleprice).toFixed(2);
downpayment = parseFloat(downpayment).toFixed(2);
loanamount = parseFloat(loanamount).toFixed(2);

function calculate()
             {
              var baseamount = Math.pow(1 + monthlyinterest, nummonths );
              return loanamount * monthlyinterest / (1 - (1/baseamount));
             }

document.write("Vehicle price: $" +vehicleprice+ "<br>");
document.write("Down payment: $" +downpayment+ "<br>");
document.write("Interest Rate: " +annualinterest+ "%<br>");
document.write("Loan Amount: $" +loanamount+ "<br>");

for (var count=2;count<=6;count+=1)
    {
    document.write(+calculate()+"<br />");
    }
</script>
</body>
</html>
4

2 回答 2

2

好的,你必须nummonths自己增加。像这样...

for (var count=2;count<=6;count+=1)
{
    document.write(+calculate()+"<br />");
    nummonths += 12;
}

此外,您可以使用http://josscrowcroft.github.io/accounting.js/进行货币格式化。

于 2013-07-10T23:53:42.277 回答
2

由于你没有使用count任何东西,你可以循环nummonths代替:

for (nummonths = 24; nummonths <= 60; nummonths += 12) {
    document.write(calculate() + "<br />");
}
于 2013-07-11T00:00:26.873 回答