javascript递归函数返回初始值

时间:2015-08-26 19:08:28

标签: javascript recursion

请,需要帮助! 我试图制作一个小型的复合计算器

function calculateCompound(amount, earning, remains, roi, compound) {
    if (remains > 0) {
        var ini_earning = earning;
        var accrual = amount * roi;
        earning = accrual * (1 - compound);
        var new_amount = amount + accrual - earning;
        var new_earning = ini_earning + earning;
        remains--;
        calculateCompound(new_amount, new_earning, remains, roi, compound);
    }  
    return earning + amount;
}

calculateCompound(100, 0, 5, .1, .5);

但是在5次调用之后它返回初始值(在这种情况下为105)

非常感谢提前!

1 个答案:

答案 0 :(得分:2)

你永远不会从递归调用中返回值,这就是它返回初始值的原因。

想法是有一个返回earning + amount的基本案例 并通过返回calculateCompound调用值

重现
function calculateCompound(amount, earning, remains, roi, compound) {
    if (remains <= 0) {
        return earning + amount;
    }

    var ini_earning = earning;
    var accrual = amount * roi;
    earning = accrual * (1 - compound);
    var new_amount = amount + accrual - earning;
    var new_earning = ini_earning + earning;

    return calculateCompound(new_amount, new_earning, remains - 1, roi, compound);
}