我正在尝试制作一个 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>