Buying a car

问题

老汪有一辆老爷车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);
       }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值