Design and implement a class calledPostfixCalculator. Use the algorithm given on
ID: 3593766 • Letter: D
Question
Design and implement a class calledPostfixCalculator. Use the algorithm given on page 374(data abstraction and problem solving with java 3rd edition) to evaluate postfix expressions, as entered into the calculator. Use only the operators +, -, *, %, and /. Assume that the postfix expressions have single digit numbersin the expression and are syntactically correct. This means that the expressions will have already been converted into correct postfix form.The PostfixCalculator should notconvert from infix to postfix form.In order to test the PostfixCalculator, it will be necessary to manuallyconvert your test expressions into postfix form before entering them into the PostfixCalculator
Explanation / Answer
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <stack>
#include <string.h>
using namespace std;
bool isOperator(char ch)
{
if (ch=='+' || ch=='-' || ch=='*' || ch=='/')
return true;
else
return false;
}
int operate(int op1, int op2, char op)
{
int ans;
switch(op){
case '+':
ans = op2 + op1;
break;
case '-':
ans = op2 - op1;
break;
case '*':
ans = op2 * op1;
break;
case '/':
ans = op2 / op1;
break;
}
return ans;
}
int main()
{
char exp1[1000], buffer[15];
string exp;
int i,op1, op2, len, j, x;
stack<int> s;
printf("Enter a Postfix Expression: ( e.g. 23 34 * ) ");
getline(cin,exp);
len = strlen(exp.c_str());
j = 0;
for(i=0; i<len;i++){
if(exp[i]>='0' && exp[i]<='9'){
buffer[j++] = exp[i];
}
else if(exp[i]==' '){
if(j>0){
buffer[j] = '';
x = atoi(buffer);
s.push(x);
j = 0;
}
}
else if(isOperator(exp[i])){
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(operate(op1, op2, exp[i]));
}
}
printf("Answer is %d ", s.top());
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.