//只有关键的运算部分有代码,只要实例化,栈是根据教科书上的写的,如果要用STL可以修改下就可以用,这个是中序表达式的运算,由于按照老师要求,可能写的有点繁琐.
#include<math.h> #include"SeqStack.h" //教科书上的顺序数组栈,改为相应的STL栈函数就可以直接实例化调用
class Calculator { public: Calculator(int sz=100):ns(sz),cs(sz){} void Run(); void Clear(); private: SeqStack<double> ns; SeqStack<char> cs; void AddOperand(double value); void DoOperator(char op); int icp(char); int isp(char); };
#include"Calcuator.h" void Calculator::DoOperator(char op) { double left,right,value; int result; ns.Pop(right); result=ns.Pop(left); if(result) switch(op) { case '+':value=left+right; ns.Push(value); break; case '-':value=left-right; ns.Push(value); break; case '*':value=left*right; ns.Push(value); break; case '/':if(right==0.0) { cerr<<"Divide by 0!"<<endl; Clear(); } else { value=left/right; ns.Push(value); } break; } else Clear(); }; void Calculator::AddOperand(double value) { ns.Push(value); } void Calculator::Run() { double newOperand; char ch='=',op,ch1; cs.Push(ch); while(cin>>ch)//第一次的括号 { if(ch=='(') cs.Push(ch); else { cin.putback(ch); break; } } while(!cs.IsEmpty()) { cin>>newOperand; ns.Push(newOperand); while(cin>>ch) { cs.getTop(ch1); if(icp(ch)>isp(ch1)) cs.Push(ch); else if(icp(ch)<isp(ch1)) { DoOperator(ch1); cs.Pop(op); cin.putback(ch); } else { cs.Pop(op); if(cs.IsEmpty()) break; } cin>>ch; if(isdigit(ch)) { cin.putback(ch); break; } else cin.putback(ch); } } ns.Pop(newOperand); cout<<"结果是:"<<endl<<newOperand<<endl; }; void Calculator::Clear() { ns.MakeEmpty(); cs.MakeEmpty(); } int Calculator::icp(char a) { switch(a) { case '=':return 0; case '(':return 6; case '*': case '/': case '%':return 4; case '+': case '-':return 2; case ')':return 1; } } int Calculator::isp(char a) { switch(a) { case '=':return 0; case '(':return 1; case '*': case '/': case '%':return 5; case '+': case '-':return 3; case ')':return 6; } }
用数组顺序栈实现表达式运算(中缀表达式)
最新推荐文章于 2021-11-09 21:43:02 发布