请,需要帮助!
我正在尝试制作一个小型js复合计算器

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)

提前谢谢了!

最佳答案

您永远不会从递归调用中返回值,这就是为什么它会返回初始值。

这个想法是有一个返回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);
}

09-26 16:17