C++ question. Please give me a complete code. and correct test example. We norma
ID: 3775513 • Letter: C
Question
C++ question. Please give me a complete code. and correct test example.
We normally write arithmetical expressions using infix notation, meaning that the operator appears between its two operands, as in "4 + 5". In postfix notation, the operator appears after its operands, as in "4 5 +". Here is a slightly more complex postfix expression: "25 12 7 - 2 * /". The equivalent infix expression is: "25 / ((12 - 7) * 2)". The result of that expression should be 2.5 (beware integer division). Postfix expressions don't require parentheses.
Write a function named postfixEval that uses a stack<double> (from the Standard Template Library) to evaluate postfix expressions. It should take a C-style string parameter that represents a postfix expression. The only symbols in the string will be +, -, *, /, digits and spaces. '+' and '-' will only appear in the expression string as binary operators - not as unary operators that indicate the sign of a number. The return type should be double. You may find the isdigit() function useful in parsing the expression. You may also use strtok() and atof().
Hint: Read a postfix expression from left to right. When you read a number, push it on the stack. When you read an operand, pop the top two numbers off the stack, apply the operator to them, and push the result on top of the stack. At the end, the result of the expression should be the only number on the stack.
Explanation / Answer
Well hee's the Complete code::
#include<iostream>
#include<string>
#include<stack>
using namespace std;
// do declare the signature of all methods here
bool isDigit(char);
bool isOperator(char);
double eval(char, double,double);
double evalPostfix(string );
bool isDigit(char C)
{
if(C >= '0' && C <= '9') return true;
return false;
}
bool isOperator(char C)
{
if(C == '+' || C == '-' || C == '*' || C == '/')
return true;
return false;
}
double evalPostfix(string exp)
{
stack<double> result;
for(int i = 0;i< exp.length();i++) {
if(isOperator(exp[i])) {
double op2 = result.top();
result.pop();
double op1 = result.top();
result.pop();
double answer= eval(exp[i], op1, op2);
result.push(answer);
}
if(isDigit(exp[i])){
int op = 0;
while(isDigit(exp[i]) &i<exp.length()) {
op = (op*10) + (exp[i] - '0');
i++;
}
i--;
result.push(op);
}
}
return result.top();
}
double eval(char operation, double op1, double op2)
{
if(operation == '+') return op1+op2;
else if(operation == '-') return op1- op2;
else if(operation == '*') return op1* op2;
else if(operation == '/' & op2!=0) return op1/ op2;
else cout<<"Unexpected Error ";
return -1;
}
int main()
{
string postfixExp;
cout<<"Enter a Postfix Expression SEPERATED BY SPACES ";
getline(cin, postfixExp);
cout<<"Answer ="<<evalPostfix(postfixExp);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.