我有点理解递归。我们从一种方法开始,它会调用自己,直到达到基本情况。请帮助我了解此代码的工作原理。我知道每次调用它时我们都会从堆栈中弹出一个对象,当达到基本情况时,我们最后会返回一个双精度值。每次调用堆栈时都会修改它吗?例如:3(回车)5(回车)*显然等于15。但是根据我查看它时的方法,我认为如果语句发送堆栈(3,5)返回5然后在第二次调用时它进入乘法发送(3,5) 并再次返回 5?为什么第二个被发送堆栈(3)而不是(3,5)?
+ (double)popOperandOffProgramStack:(NSMutableArray *)stack
{
double result = 0;
id topOfStack = [stack lastObject];
if (topOfStack) [stack removeLastObject];
if ([topOfStack isKindOfClass:[NSNumber class]])
{
result = [topOfStack doubleValue];
}
else if ([topOfStack isKindOfClass:[NSString class]])
{
NSString *operation = topOfStack;
if ([operation isEqualToString:@"+"]) {
result = [self popOperandOffProgramStack:stack] +
[self popOperandOffProgramStack:stack];
} else if ([@"*" isEqualToString:operation]) {
result = [self popOperandOffProgramStack:stack] *
[self popOperandOffProgramStack:stack];
} else if ([operation isEqualToString:@"-"]) {
double subtrahend = [self popOperandOffProgramStack:stack];
result = [self popOperandOffProgramStack:stack] - subtrahend;
} else if ([operation isEqualToString:@"/"]) {
double divisor = [self popOperandOffProgramStack:stack];
if (divisor) result = [self popOperandOffProgramStack:stack] / divisor;
}
}
return result;
}