稅務計算中未定義的遞迴
在此遞歸稅務運算函數中:
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中文網其他相關文章!