計祘客 棧 加減乘除
阿新 • • 發佈:2019-01-05
#include<cstdio> #include<stack> #include<map> #include<cmath> #include<iostream> #include<cstring> using namespace std; const int elength=30; int ans=0; stack<int>s1; stack<char>s2; void Caculate() { char t; int t1,t2; t=s2.top(); s2.pop(); t1=s1.top(); s1.pop(); t2=s1.top(); s1.pop(); //cout<<"t1£º"<<t1<<" "<<t2<<endl; if(t=='*') { ans=t1*t2; s1.push(ans); } if(t=='^') { ans=pow(t2,t1); s1.push(ans); } if(t=='+') { ans=t1+t2; //cout<<t1<<" "<<t2<<endl; s1.push(ans); } if(t=='-') { ans=t2-t1; s1.push(ans); } if(t=='/') { ans=t2/t1; s1.push(ans); } } int main() { map<char,int> m; char c[elength]; //memset(c,0,sizeof(c)); int temp;
\\定義運算子的優先順序 m['+']=1; m['-']=1; m['*']=2; m['/']=2; m['^']=3; //stringstream ss; //getline(cin,c); //ss<<c; //while(ss>>r) cin>>c; int i=0; int cnt=0; int ii; while(1) { temp=0; ii=0; for(;c[i]-'0'>=0&&c[i]-'0'<=9;i++) { s1.push(c[i]-'0'); } cnt++;//記錄棧內應該有多少個元素 while(s1.size()>=cnt) { //cout<<"top"<<s1.top()<<endl; temp=temp+s1.top()*pow(10,ii++); s1.pop();//將數字字符合成數字 } //cout<<"temp:"<<temp<<endl; s1.push(temp); if(c[i]=='\0') break; if(s2.empty()||m[c[i]]>m[s2.top()]) s2.push(c[i]); else { while(!s2.empty()) { Caculate(); cnt=1;//完成一次計算後棧內只有一個元素 } s2.push(c[i]); } i++; } while(!s2.empty()) Caculate(); ans=s1.top(); cout<<ans<<endl; }
首先設立兩個棧,一個存放數字,一個存放字串(加減乘除乘方),然後分別入棧。
當即將入棧的符號的運算級大於棧頂的運算級,直接入棧。如果即將入棧的符號運算級小於等於棧頂,則先把棧內的式子先出棧計算,注意的是數字字元轉換成數字。