后缀表达式实现六则运算

来源:互联网 发布:单片机交通灯课程设计 编辑:程序博客网 时间:2024/06/06 00:28

实现后缀表达式的类如下,该类计算的是已经处理好的后缀表达式。

#include<iostream>#include<stack>#include<string>using namespace std;void StringDevide(string str,int &num,string st1[]){for(int i=0;i<100;i++)st1[i][0]='\0';int n=str.size();int j=0,count=0;for(int i=0;i<n;i++){if(str[i]!=' '){st1[count].push_back(str[i]);}else{count++;}}num=count+1;}void StringToNum(string str,int &num){num=0;int n=str.size();for(int i=0;i<n;i++){num=num*10;num+=str[i]-'0';}}class InterTreeComputer{private://要计算的表达式string m_expresion;//将数字存储到栈中stack<int> m_num;public:InterTreeComputer(string expression):m_expresion(expression){}//判定某一操作符是否是运算符bool IsOperator(char ch)const;//获取要计算的两个运算数void GetOperands(int &left,int &right);//对获取的两个数按照符号ch进行计算int computer(int left,int right,char ch)const;//获取表达式string GetPostoperation()const;void SetPostoperator();//计算表达式并返回结果int Evaluate();};bool InterTreeComputer::IsOperator(char ch)const{switch(ch){case '+':case '-':case '*':case '/':case '%':case '^':return 1;default:return 0;}}void InterTreeComputer::GetOperands(int &left,int &right){if(m_num.empty()){cout<<"num stack is empty!";return ;}right=m_num.top();m_num.pop();if(m_num.empty()){cout<<"the expression is wrong!"<<endl;return ;}left=m_num.top();m_num.pop();}int InterTreeComputer::computer(int left,int right,char ch)const{switch(ch){case '+':return left+right;break;case '-':return left-right;break;case '*':return left*right;break;case '/':if(right==0){cout<<"the expression is wrong"<<endl;return -1;}return left/right;break;case '%':return left%right;break;case '^':if(left==0&&right==0){cout<<"the expression is wrong"<<endl;return -1;}int value=1;while(right>0){value*=left;right--;}return value;break;}}string InterTreeComputer::GetPostoperation()const{return m_expresion;}void InterTreeComputer::SetPostoperator(){}int InterTreeComputer::Evaluate(){string *str=new string[100];int num;StringDevide(m_expresion,num,str);for(int i=0;i<num;i++){if(str[i][0]=='+'||str[i][0]=='-'||str[i][0]=='*'||str[i][0]=='/'||str[i][0]=='%'||str[i][0]=='^'){char ch=str[i][0];int left,right;GetOperands(left,right);int number=computer(left,right,ch);m_num.push(number);}else{int numb=0;StringToNum(str[i],numb);m_num.push(numb);}}return m_num.top();}


测试的CPP文件如下:

#include<iostream>using namespace std;#include<string>#include<stack>#include"InterTreeComputer.h"int main(){string str="2 5 + 3 * 8 3 / -";string st1="2 3 ^ 1 +";string st2="2 2 3 ^ ^ 4 /";InterTreeComputer Comp(st2);cout<<Comp.GetPostoperation()<<endl;cout<<Comp.Evaluate()<<endl;return 0;}


什么是后缀表达式?
那就先说普通的算式 1+2*3-4 。这里,操作符+,-,*,/都是在表达是中间的情况叫做中缀表达式。中缀表达式,有一个特点就是有的时候,需要括号来表示优先级。
后缀表达式是计算机中常用的表达式,又叫逆波兰表达式(因为波兰表达式是前缀表达式,呵呵)。因为他并没有括号,所以计算表达更加简便。 例如 1+2*3-4 的后缀表达式就是 1 2 3 * + 4 - 。他的本质是有一个栈,先压入三个数1 2 3 ,然后发现了下一个是*,就将栈的头两个拿出来做乘法,也就是2*3,结果得6,在压入那个栈中。然后依次类推。

原创粉丝点击