简体   繁体   中英

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

I have to write a program that, given an initial sum of money (principal), returns me how many years this sum has to be kept in the bank in order for it to amount to the desired amount of money (desired). The interest is paid yearly, and the new sum is re-invested yearly after paying tax. The principal is not taxed but only the year's accrued interest.

When I try to test the program with this numbers: principal: 1000 interest: 0.01625 tax: 0.18 desired: 1200

I should get 14 years as a result, but I get 12 instead.

There's probably a logical error about how I implemented the loop, but can't figure it out.

 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

A different way to do it:

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

If you ever need to compute the something that would take a few billions of years or more, this should be faster :P

Also, your take a bit too much if desired is below your principal (and your interest positive and tax lower than interest), it would enter in an infinite loop, you have to take care of that!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM