请,需要帮助! 我试图制作一个小型的复合计算器
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)
非常感谢提前!
答案 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);
}