该任务的一部分包括在显示屏上打印出当前要求解的方程,为此我使用以下方法:
+ (NSString *)descriptionOfTopOfStack:(NSMutableArray *)stack {
NSMutableString *programFragment = [NSMutableString stringWithString:@""];
id topOfStack = [stack lastObject];
if (topOfStack) [stack removeLastObject];
if ([topOfStack isKindOfClass:[NSNumber class]]) {
[programFragment appendFormat:@"%g", [topOfStack doubleValue]];
} else if ([topOfStack isKindOfClass:[NSString class]]) {
NSString *operation = topOfStack;
if ([self isDoubleOperandOperation:operation]) {
[programFragment appendFormat:@"(%@ %@ %@)", [self descriptionOfTopOfStack:stack], operation, [self descriptionOfTopOfStack:stack]];
} else if ([self isSingleOperandOperation:operation]) {
[programFragment appendFormat:@"%@( %@ )", operation, [self descriptionOfTopOfStack:stack]];
} else if ([ self isNoOperandOperation:operation]) {
[programFragment appendFormat:@"%@", operation];
} else if ([self isVariable:operation]) {
[programFragment appendFormat:@"%@", operation];
}
}
return programFragment;
}
+ (NSString *)descriptionOfProgram:(id)program {
NSMutableArray *stack;
if ([program isKindOfClass:[NSArray class]]) {
stack = [program mutableCopy];
}
return [self descriptionOfTopOfStack:stack];
}
我的程序计算结果,一切都很好,唯一的问题是,当我输入变量、数字或单操作数运算时,显示器只显示最后一个条目,因为它不会继续迭代存在的其余值数组,因为没有进行其他递归调用,知道如何让程序在整个堆栈中执行而不破坏输出吗?