簡體   English   中英

循環執行不正確,無法弄清楚我在做什么

[英]Loop implemented incorrectly, can't figure out what I'm doing wrong

我必須編寫一個程序,給定初始金額(本金),然后向我返回必須將這筆款項保留在銀行中多少年才能使其達到期望的金額(所需)。 利息每年支付一次,新的金額每年在繳稅后重新投資。 本金不征稅,僅當年的應計利息。

當我嘗試使用以下數字測試程序時:本金:1000利息:0.01625稅:0.18所需:1200

結果我應該得到14年,但是我得到12年。

關於如何實現循環可能存在邏輯錯誤,但無法弄清楚。

 function calculateYears(principal, interest, tax, desired) { year = 0; if (principal == desired) { return year; } else { while (principal < desired) { interestBeforeTaxes = principal * interest; taxes = interestBeforeTaxes * interest; finalInterest = interestBeforeTaxes - taxes; principal += finalInterest; year += 1; } return year; } } console.log( calculateYears(1000, 0.01625, 0.18, 1200) ); 

剛剛測試過,應該是

taxes = interestBeforeTaxes * tax

一種不同的方法:

Math.ceil(Math.log(desired / principal) / Math.log(1 + interest * (1 - tax)))

如果您需要計算將花費數十億年甚至更長的時間,那么它應該更快:P

此外,您需要多一點的如果需要的話是你的本金下方(與你的興趣正和稅收比利息低),它會在一個無限循環進入,你必須采取照顧太多了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM