我正在尝试制作一个简单的信用卡还款计算器脚本,但似乎遇到了“while”循环的问题。它适用于较低的数字,但当你开始输入更高的数字时,它会冻结浏览器,然后你必须退出并重新打开。
这是我的JavaScript(jQuery):
$('#calculate').click(function()
{
var currentBalance = parseFloat($('#current_balance').val().substring(1)); // substring so it doesnt grab the £ sign
var interestRate = parseFloat($('#interest_rate').val());
var interestType = $('#interest_type').val();
var monthlyPayment = parseFloat($('#monthly_payment').val().substring(1));
var totalInterest = 0;
var interest = 0;
var months = 0;
while(currentBalance > 0) // while there is still a balance on the card run the following
{
interest = (currentBalance/100)*interestRate; // find interest amount for this month
currentBalance = currentBalance+interest; // add the interest to the balance
currentBalance = currentBalance-monthlyPayment; // subtract monthly payment from balance
totalInterest = totalInterest+interest; // total amount of interest paid
months++;
}
var years = parseInt(months / 12);
var remainingMonths = months % 12;
totalInterest = Math.round(totalInterest);
$('#clear_balance').val(years+' years and '+remainingMonths+' months');
$('#interest_paid').val('£'+totalInterest);
});
这是我的HTML:
<table id="card-info">
<tbody>
<tr>
<td><label for="current_balance">Current balance</label></td>
<td><input type="text" id="current_balance" /></td>
</tr>
<tr>
<td><label for="interest_rate">Interest rate</label></td>
<td>
<input type="text" id="interest_rate" />
<select id="interest_type">
<option value="monthly">Monthly</option>
<option value="yearly">Yearly</option>
</select>
</td>
</tr>
<tr>
<td><label for="monthly_payment">Monthly payment</label></td>
<td><input type="text" id="monthly_payment" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="2"><button id="calculate">Calculate</button></td>
</tr>
</tbody>
</table>
</div>
<div id="results">
<table id="results-info">
<tbody>
<tr>
<td>
<label for="clear_balance">Time to clear balance</label><br />
<input type="text" id="clear_balance" />
</td>
<td>
<label for="interest_paid">Total interest paid</label><br />
<input type="text" id="interest_paid" />
</td>
</tr>
</tbody>
</table>
我有什么问题吗?
答案 0 :(得分:5)
您的代码没有考虑到每月支付的金额不足以支付每个月的利息。
在这种情况下,它会进入一个无限循环,因为贷款永远不会得到回报!
答案 1 :(得分:0)
你的当前平衡永远是积极的!