Calculator with Stacks & Precedence
Feb 18, 2014 at 5:05pm UTC
I am writing methods for a Calculator class which uses two stacks, one for int and one for char. The calculator should check the precedence of the operator before placing it on the stack to determine if the operation has higher precedence than the one currently on the stack. If the operation has high precedence, the operation is performed and the result is placed on the operand stack.
Here is what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
void Calculator::processOperator ()
{
int temp;
while ((!operators.isEmpty())
{
int x = operands.peek();
operands.pop();
int y = operands.peek();
operands.pop();
char op = operators.peek();
operators.pop();
switch (op)
{
case '+' : temp = x + y;
break ;
case '-' : temp = x - y;
break ;
case '*' : temp = x * y;
break ;
case '/' : temp = x / y;
break ;
default : cout << "Invalid operator, press any key to terminate." ;
}//end switch
operands.push(temp);
}//end while
}//end processOperator()
bool Calculator::higherPrecedence(char op)
{
if (op >= operators.peek())
{
return true ;
}// end if
else
{
return false ;
}//end else
}//end higherPrecedence()
int Calculator::calculate ()
{
cout << "Please enter an expression: " << endl;
cin >> expression;
for (int i; i < expression.length(); i++)
{
if (higherPrecedence(op) == false ) //if a
{
if (!isOperator(expression[i]))// if b
{
int tempOp = getOperand(i);
operands.push(tempOp);
}//end if b
else if (isOperator(expression[i]))
{
operators.push(expression[i]);
}//end for
}//end if a
else
{
processOperator();
}
char op = operands.peek();
higherPrecedence(op);
}//end for
}//end calculate()
Last edited on Feb 18, 2014 at 6:32pm UTC
Feb 18, 2014 at 9:38pm UTC
bump
Topic archived. No new replies allowed.