感觉愚蠢,但我真的不明白这一点。阶乘函数递归
在下面的代码中,为什么else if
语句中的递归在达到1时停止?它不应该最终返回-1并继续返回到无穷?
- (int)factorial:(int)operand
{
if (operand < 0) return -1;
else if (operand > 1) return operand * [self factorial:operand - 1];
else return 1;
}
感觉愚蠢,但我真的不明白这一点。阶乘函数递归
在下面的代码中,为什么else if
语句中的递归在达到1时停止?它不应该最终返回-1并继续返回到无穷?
- (int)factorial:(int)operand
{
if (operand < 0) return -1;
else if (operand > 1) return operand * [self factorial:operand - 1];
else return 1;
}
让我们看到这个步骤。
[self factorial:3]
return 3 * [self factorial:2];
return 3 * (2 * [self factorial:1]);
return 3 * (2 * (1 * [self factorial:0]));
return 3 * (2 * (1 * (1))) // Reached to return 1;
所以递归只是一次又一次地调用该方法,直到你达到某种基本情况。让我们看看operand
等于一个会发生什么:
if (operand < 0) return -1;
这是不小于零,以便继续下一条款。
else if (operand > 1) return operand * [self factorial:operand - 1];
它不是> 1它等于1因此转到下一个子句。
else return 1;
这是它必须,所以返回1
非常感谢!我知道这是一个基本问题,所以非常感谢您花时间回答。我接受了@scha的答案,仅仅因为对我来说它更清晰。 – rapcal
谢谢,@scha!非常清楚和有帮助。 – rapcal