我正在尝试制作一个逆波兰计算器程序,并希望有一个标签显示您输入的表达式。如果您输入3,5,4,+,/,则标签将显示((4+5) / 3)。我在实现时遇到了困难。我使用一个名为stack的mutableArray来保存数字和操作符。另一个主要问题是传递的字符串不会是完整的字符串,而是每次用户输入值时都会传递,因此程序必须连续运行,只有一个或两个堆栈项。以下是代码。
+ (NSString *)descriptionOfProgram:(id)program
{
NSMutableArray *stack;
if([NSArray isKindOfClass:[NSArray class]])
stack = [program mutableCopy];
NSUInteger count = [stack count];
NSString* symbol;
NSMutableString *result;
[result appendString:@"("];
for( NSUInteger i=0; i<count; i++){
if ([[stack lastObject] isEqualToString:@"+"] || [[stack lastObject] isEqualToString:@"-"] || [[stack lastObject] isEqualToString:@"/"] || [[stack lastObject] isEqualToString:@"*"] || [[stack lastObject] isEqualToString:@"sin"] || [[stack lastObject] isEqualToString:@"cos"] )
{
symbol = [stack lastObject];
[stack removeLastObject];
}
else
{
if( [stack lastObject] != nil){
[result appendString:[stack lastObject]];
[stack removeLastObject]; }
// [result stringByAppendingString:symbol];
if( [stack lastObject]){
[result appendString:[stack lastObject]];
[stack removeLastObject];}
[result appendString:@")"];
[stack addObject:result];
}
}
return [stack lastObject];
}