Mr. Wang has an old car that costs about 2000 yuan and is easy to sell. He took a fancy to a 8000-dollar second-hand car and wanted to buy it after saving enough money. He estimated that he could save 1000 yuan a month. Mr. Wang has an old car that costs about 2000 yuan and is easy to sell.
He took a fancy to a 8000-dollar second-hand car and wanted to buy it after saving enough money.
He estimated that he could save 1000 yuan a month.
His current car and the second-hand car will cut prices every month. At first, it will drop by 1%. Then, the cut will increase by 0.5% every two months.
For example, the price will be reduced by 1% in the first month, 1.5% in the second month, 1.5% in the third month, and 2% in the fourth month.
In other words, the price cut for each subscription month is the same as that for the previous month. In the double month, the price cut is increased by 0.5% compared with the previous month.
Can you help him?
How many months does he have to save to buy the used car? How much money can he leave after buying a car?
The function prototype is as follows:
NbMonths (startPriceOld, startPriceNew, savingperMonth, percentLossByMonth)
Corresponding to: old car price, second-hand car price, monthly deposit quota, decline in the first month
Example:
nbMonths(12000, 8000, 1000, 1.5) // [0, 4000]
In this case, the old car is more valuable than the second-hand car. What is it? Buy it directly! You can earn 4000 RMB!
nbMonths(8000, 8000, 1000, 1.5) // [0, 0]
In this case, the old one is replaced by a new one, and the old one is replaced by a new one.
nbMonths(2000, 8000, 1000, 1.5) // [6, 766]
In this case, it takes six months, and the remaining balance is 766, 158, and so on.
This question is a simple addition, subtraction, multiplication, division, but you should not think too much about it, such as deposit bank interest ~
Okay, go directly to the Code:
function nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth){ percentLossByMonth /= 100; var months = 1; var percentLossIncrement = 0.005; var alreadyHaveMoney = 0; while(startPriceOld + alreadyHaveMoney < startPriceNew){ if(months % 2 === 0){ percentLossByMonth += percentLossIncrement; } startPriceOld *= (1 - percentLossByMonth); startPriceNew *= (1 - percentLossByMonth); alreadyHaveMoney += savingperMonth; months++; } return [months-1,Math.round(startPriceOld + alreadyHaveMoney - startPriceNew)]; }
The above is the JavaScript interesting question: Buy a car content, for more information, please follow the PHP Chinese Network (www.php1.cn )!