In: Computer Science
Let's try to develop a C++ Reverse Polish Notation (RPN) calculator!
Create a base class called Operand
Derive a class called Number from Operand
Derive a class called Operator from Operand
Derive a class called Add from Operator (2 + 3 = 5)
Derive a class called Subtract from Operator (5 - 2 = 3)
Derive a class called Multiply from Operator (5 * 3 = 15)
Derive a class called Divide from Operator (18 / 6 = 3)
Derive a class called Square from Operator (3 ^ 2 = 9)
Almost all of the above classes are going to be "empty" classes
In a separate file, create a function called Calculate() that must do the following:
Develop some C++ code in the main() function that uses your Calculate() function by doing the following:
Simpler Example Code:
std::queue<Operand *> a;
a.push_back(new Number(1));
a.push_back(new Number(2));
a.push_back(new Add());
std::cout << Calculate(a); // Prints 3
Here i am providing the answer, Hope it helps, please give me a like, it helps me a lot.
Here is the C++ Reverse Polish Notation calculator....
#include<iostream.h>
#include<math.h>
#include<cstdlib.h>
#include<sstream>
#include<vector>
#include<iterator>
#include<algorithm>
#include<string>
double rpn(const std ::string &expr){
std :: istringstream iss(expr);
std :: vector<double> stack;
std :: cout <<"input\toperation\tstack after"<<std ::end1;
std :: string token;
while( iss >> token) {
std :: cout << token << "\t";
double tokenNum;
if ( std :: istringstream(token) >> tokenNum ) {
std :: cout << "push\t\t";
stack.push_back(tokenNum);
} else {
std :: cout <<"operator\t\t";
double secondOperator = stack.back();
stack.pop_back();
double firstOperand = stack.back();
stack.pop_back();
if(token == "*" )
stack.push_back(firstOperand*secondOperand);
else if(token == " / ")
stack.push_back( firstOperand / secondOperand);
else if(token == " - ")
stack.push_back( firstOperand - secondOperand);
else if(token == " + ")
stack.push_back( firstOperand + secondOperand);
else if(token == " ^ ")
stack.push_back( std : : pow(firstOperand,secondOperand));
else {
std : : cerr << "error" << std :: end1;
std :: exit(1);
}
}
std : : copy (stack.begin(),stack.end(),std :: ostream_iterator<double>(std :: cout, " "));
std : :cout<<std : : end1;
}
return stack.back();
}
int main() {
std : : string s = " " ;
std : : cout << "final answer : " << rpn(s) << std :: end1;
return 0;
}
thank you. please like.