Hi, I'm experimenting with an algorithm for simplifying string expressions. I have a postfix expression, and just for testing I entered it in code. It is 123*+4-, derived from the infix 1+2*3-4. However, the simplifying isn't working. I thought it was because of a char to int conversion, but I took care of that and it's working for the first operation it sees, but not for the others. Here's the relevant code:
Code:
//All operands are pushed into the stack in order of scanning
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^')
{
NSLog(@"Operator: %c", c);
char temp = [[stack lastObject] charValue];
NSLog(@"Temp should be %@", [stack lastObject]);
[stack removeLastObject];
int retVal;
NSLog(@"Operand 1 (current topStack): %c", [[stack lastObject] charValue]);
NSLog(@"Operand 2 (temp): %c", temp);
char last = [[stack lastObject] charValue];
if (c == '+')
retVal = (last - 48) + (temp - 48); //Char conversions
else if (c == '-')
retVal = (last - 48) - (temp - 48);
else if (c == '*')
retVal = (last - 48) * (temp - 48);
else if (c == '/')
retVal = (last - 48) / (temp - 48);
else if (c == '^')
retVal = pow((temp - 48), (last - 48));
NSLog(@"RetVal: %i", retVal);
[stack removeLastObject];
[stack addObject:[NSNumber numberWithChar:retVal]];
NSLog(@"%@ added to stack", [stack lastObject]);
NSLog(@"-------Ended operator %c", c);
}
The output makes sense for only the first operation:
Code:
1 added to stack
2 added to stack
3 added to stack
Operator: *
Temp should be 51
Operand 1 (current topStack): 2
Operand 2 (temp): 3
RetVal: 6
6 added to stack
-------Ended operator *
Operator: +
Temp should be 6
Operand 1 (current topStack): 1 //Correct
Operand 2 (temp): //???Should be 6 (the last added object to the stack)
RetVal: -41
-41 added to stack
-------Ended operator +
4 added to stack
Operator: -
Temp should be 52
Operand 1 (current topStack): ◊ //???
Operand 2 (temp): 4
RetVal: -93
-93 added to stack
-------Ended operator -
Value: (
"-93"
)
Thanks for any help, because I don't get this at all.