贷款计算的递归方法

时间:2015-11-10 00:28:27

标签: java recursion

我试图编写一个递归方法,该方法需要3个参数(贷款金额,利率和每月付款)。利息每月复利。目标是找出完全还清贷款需要多少个月。这是我到目前为止的代码:

    public static double loanLength(double loan, double interest, double payment) {
    if (payment > loan + loan * interest) {
        return 0;
    } else {
        double completeLoan = loan + (loan * interest);
        double stillOwe = completeLoan - payment;
        if (stillOwe <= 0) {
            return 1;
        } else {
            return 1 + (loanLength(stillOwe, interest, payment));
        }

    }

EXPECTED返回的示例包括:

loanLength(1000,0.10,200)在6个月内还清

loanLength(0,0.90,50)为0个月

但我的回报如下:

loanLength(1000,0.10,200):7个月

loanLength(0,0.90,50):0个月

我的第二个测试工作正常,但我的第一个测试只比它应该的1个整数。我无法弄清楚为什么。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

public static int loanLength(double loan, double interestAPR, double payment) {
    if (loan <= 0) {
        return 0;
    }
    double monthlyInterest = interestAPR / (12 * 100);
    double compounded = loan * (1 + monthlyInterest);
    return 1 + loanLength(compounded - payment, interestAPR, payment);
}

public static void main(String[] args) {
    System.out.println(loanLength(0, 0.90, 50)); // 0
    System.out.println(loanLength(1000, 10.0, 200)); // 6
    System.out.println(loanLength(1000, 0.1, 200)); // 6 (FWIW)
}

请注意,利息APR按表示,即10%年利率的10,000美元贷款和每月500美元的付款计算为

loanLength(10000, 10.0, 500);

如果0.10 = 10%APR,则更改此行

double monthlyInterest = interestAPR / 12;