我試圖從JavaScriptx中的MITx 6.00.1x中查看問題集作爲學習練習,以嘗試更好地處理如何在JS中處理算法問題求解問題,而不僅僅是使用框架/庫和DOM操作像我已經有一段時間了,但在第二個問題集的第一次分配時,在for循環的第二次迭代之後,我的值始終關閉。貸款計算中始終關閉的值
僅供參考,這裏有測試用例,收支= 42,年利率= 0.2,月度償付率= 0.04正確的價值觀:
月1餘額:40.99
月2餘額:40.01
個月3餘額:39.05
月4餘額:38.11
月5剩餘的平衡:37.2
月6剩餘的平衡:36.3
月7剩餘的平衡:35.43
月8餘額:34.58
月9剩餘平衡:33.75
第10天餘額:32.94
蒙特H 11餘款:32.15
月12餘款:31.38
我從我的代碼獲得的數值,雖然是:
月1餘額:40.992
第2月餘額:40.035
第3個月餘額:39.101
月4餘額:38.188
月5剩餘的平衡:37.297
月6剩餘的平衡:36.427
月7剩餘的平衡:35.577
月8餘額:34.747
第9月剩餘餘額:33.936
月10餘額:33.144
月11餘額:32.371
月12餘額:32。371
這是我的代碼,僅供參考。
//Function calculates the amount outstanding on a loan after one year of paying the exact minimum amount, assuming compound interest
function balanceAfterYear(balance, annualInterestRate, monthlyPaymentRate) {
\t //Rate at which interest builds monthly
\t var monthlyInterest = annualInterestRate/12.0
\t //The minimum monthly payment, defined by the monthly payment rate (as a decimal) multiplied by the current outstanding balance
\t var minPayment = monthlyPaymentRate * balance;
\t //The unpaid balance for a given month is equal to the previous month's balance minus the minimum monthly payment
\t var unpaidBalance = balance - minPayment;
\t //the updated balance for a given month is equal to the unpaid balance + (the unpaid balance * the monthly interest rate). Initialized at 0 here because this does not apply during month 0 which is what the above values represent.
\t var updatedBalance = 0;
\t for (var i = 1; i < 12; i++) {
\t \t minPayment = monthlyPaymentRate * unpaidBalance;
\t \t updatedBalance = unpaidBalance + (unpaidBalance * monthlyInterest);
\t \t unpaidBalance = updatedBalance - minPayment;
\t }
\t return updatedBalance.toFixed(2);
}
我是在我只是沒有察覺的邏輯做一個基本的錯誤?這是一個四捨五入的問題(即在進行計算時舍入值而不是在最後的幫助中)?我是否錯過了現在應該知道的有關JavaScript的基礎知識?
我希望這不會被標記爲轉貼,因爲我知道很多人在過去提過類似的問題,但幾乎肯定不是在js中。
謝謝你的時間。現在有種像白癡的感覺,因爲我可以在沒有任何困難的情況下在Python中做到這一點。
如果你只是使用調試器,並通過功能步驟,我相信你可以找到問題 – Huangism
[是浮點運算破](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – adeneo