问题
老汪有一辆老爷车2000块,他想卖掉这两车去买一辆8000块的新车,已知老汪每个月能攒1000块钱,而且无论是新车还是旧车,每个月的价格下降a=1.5%。a这个值每隔2个月会增加5%。那么老汪需要几个月才能卖掉老爷车买得起新车,买车之后还剩多少钱。
现在给几个参数:老爷车的价格startPriceOld,新车的价格startPriceNew,每个月攒的钱savingperMonth,每个月价格下降多少percentLossByMonth,求出需要几个月才能卖掉老爷车买得起新车,买车之后还剩多少钱。
例子
nbMonths(12000, 8000, 1000, 1.5) should return [0, 4000]
nbMonths(8000, 8000, 1000, 1.5) should return [0, 0]
代码
package codewars;
public class BuyCar {
public static int[] nbMonths(int startPriceOld, int startPriceNew, int savingperMonth, double percentLossByMonth) {
double priceOld = startPriceOld;
double priceNew = startPriceNew;
double saveTotal = 0;
double percent = percentLossByMonth;
int month = 0;
double left = 0;
while (true) {
//判断是不是买得起车
if (priceOld + saveTotal >= priceNew) {
left = priceOld + saveTotal - priceNew;
break;
}
month++;
//每隔两个月价格下降比值会变化
if (month%2 == 0) {
percent = percent + 0.5;
}
System.out.println(1-percent/100);
priceOld = priceOld * (1-percent/100);
priceNew = priceNew * (1-percent/100);
saveTotal += savingperMonth;
}
int[] result = new int[2];
result[0] = month;
result[1] = (int)Math.round(left);
return result;
}
public static void main(String[] args) {
int[] a = BuyCar.nbMonths(12000, 8000, 1000, 1.5);
}
}