首页 >web前端 >js教程 >为什么这个递归税务计算函数会导致未定义的递归?

为什么这个递归税务计算函数会导致未定义的递归?

Susan Sarandon
Susan Sarandon原创
2024-12-19 22:04:12983浏览

Why Does This Recursive Tax Calculation Function Result in Undefined Recursion?

税务计算中未定义的递归

在此递归税务计算函数中:

function taxes(tax, taxWage) {
    var minWage = firstTier; //defined as a global variable
    if (taxWage > minWage) {
        //calculates tax recursively calling two other functions difference() and taxStep()
        tax = tax + difference(taxWage) * taxStep(taxWage);
        var newSalary = taxWage - difference(taxWage);
        taxes(tax, newSalary);
    } else {
        returnTax = tax + taxWage * taxStep(taxWage);
        return returnTax;
    }
}

递归无法终止。具体来说,问题在于调用递归调用的函数臂:

if (taxWage > minWage) {
    // calculates tax recursively calling two other functions difference() and taxStep()
    tax = tax + difference(taxWage) * taxStep(taxWage);
    var newSalary = taxWage - difference(taxWage);
    taxes(tax, newSalary);
}

这里,函数不返回任何值或设置 returnTax 变量。当函数没有显式返回时,它默认返回 undefined。因此,递归会无限期地继续,从而导致未定义的结果。

要解决此问题,您应该修改这部分代码,如下所示:

if (taxWage > minWage) {
    // calculates tax recursively calling two other functions difference() and taxStep()
    tax = tax + difference(taxWage) * taxStep(taxWage);
    var newSalary = taxWage - difference(taxWage);
    return taxes(tax, newSalary);
}

此更改可确保函数返回递归调用的结果,正确地将值沿着递归链传播。

以上是为什么这个递归税务计算函数会导致未定义的递归?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn