#include <iostream> #include <string> #include <list> using namespace std; const int PLUS = -1,MINUS=-2,MUL=-3,DIV=-4,LPREN=-5,RPREN=-6,EOE=-7; string expr; int pos; int NextToken() { int t=0; switch(expr[++pos]){ case '+':t=PLUS;break; case '-':t=MINUS; break; case '*':t=MUL;break; case '/':t=DIV;break; case '(':t=LPREN;break; case ')':t=RPREN;break; case '/0':t=EOE;break; default: while(isdigit(expr[pos])){ t=t*10+expr[pos++]-'0';} --pos; break; } return t; } int opvalue(int a,int b, int op){ switch (op) { case PLUS:return a+b; case MINUS:return a-b; case MUL:return a*b; case DIV:return a/b; } return 0; } #define calc a=S2.back();S2.pop_back(); b=S2.back();S2.pop_back();S2.push_back(opvalue(b,a,p)); int Evalue() { list<int> S1, S2; int t,p,a,b; while((t=NextToken())!=EOE) { if (t>=0)S2.push_back(t); else if(t>-5&&t<0) { p=S1.empty()?-8:S1.back(); while(!S1.empty()&&p!=LPREN&&(p<-2||t>-3)) { calc S1.pop_back();p=S1.back();} S1.push_back(t); } else if(t==RPREN) { p=S1.back(); while (p!=LPREN){ calc; S1.pop_back();p=S1.back(); } S1.pop_back(); } else S1.push_back(t); } while(!S1.empty()){p=S1.back(); calc S1.pop_back();} return S2.back(); } int main() { //freopen("expr.txt","r",stdin); cin>>expr; pos=-1; cout<<Evalue()<<endl; }
表达式求值
最新推荐文章于 2024-07-17 19:31:11 发布