2017-06-01 82 views
0

我試圖從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中做到這一點。

+0

如果你只是使用調試器,並通過功能步驟,我相信你可以找到問題 – Huangism

+3

[是浮點運算破](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – adeneo

回答

0

它看起來像你不需要截斷你的數字。您的銀行賬戶會將您的資金記錄到分數小數點後兩位。例如,在支付利息後,您的第一個月的餘額應該是40.99美元,而不是40.992美元。無論是截斷還是四捨五入。我認爲每個後續月份加上第三位小數點後的錯誤介紹。您可能想看到JavaScript math, round to two decimal places

+0

非常感謝你的禮貌和洞察力的答案。如果我有這樣的聲譽,我會鼓勵你。 – TrypanosomaBruceii

+0

@TrypanosomaBruceii不客氣,我希望它有幫助。 –

0

您的算法錯誤。所有你需要做的是扣除支付和計息:

function f(b, r, m) { 
 
    for (var i = 0; i < 12; i++) { 
 
    b = b*(1-m)*(1+r/12); 
 
    } 
 
    return b.toFixed(2); 
 
} 
 

 
console.log(f(42, 0.2, 0.04));

+0

非常感謝你,在我以前正確寫入的東西中,像這樣的基本算法錯誤非常令人尷尬。我應該知道,比責備語言和提出問題更好,而不是考慮我在基本層面上做錯了(更可能)的可能性。 – TrypanosomaBruceii