# Golden Thumb

1-on-1 tutor of chosen kids

• 博客访问：

## 小c++程序示例，解析并计算算术表达式如 2 + 3 * ( 4 - 5 ) * ( 6 - ( 7 - 8 ) ) + 9

(2021-02-01 13:17:27) 下一个

#include<iostream>
#include<map>
using namespace std;
class S{
private:
int t=0;
char a[50];
public:
void pu(char c){a[t++]=c;}
char po(){return a[--t];}
char pe(){return a[t-1];}
bool em(){return t==0;}
};
int main(){
map<char,int>m={{'+',10},{'-',10},{'*',20},{'/',20}};
S s;
char c;
string x,y="";
while(cin>>x){
if(x=="(")s.pu(x[0]);
else if(x==")")while((c=s.po())!='(')y=y+c+' ';
else if(m.find(x[0])!=m.end()){
while(!s.em()&&m[s.pe()]>=m[x[0]])y=y+s.po()+' ';
s.pu(x[0]);
}else y+=x+' ';
}
while(!s.em())y=y+s.po()+' ';
cout<<y<<endl;
return 0;
}

\$ g++ -std=c++11 -Wall gt.cpp && ./a.out
2 + 3 * ( 4 - 5 ) * ( 6 - ( 7 - 8 ) ) + 9
2 3 4 5 - * 6 7 8 - - * + 9 +

#include<iostream>
using namespace std;
class S{
private:
int t=0;
int a[50];
public:
void pu(int s){a[t++]=s;}
int po(){return a[--t];}
};
int main(){
S s;
string x;
while(cin>>x){
if(x=="+")s.pu(s.po()+s.po());
else if(x=="-")s.pu(-s.po()+s.po());
else if(x=="*")s.pu(s.po()*s.po());
else if(x=="/"){int x=s.po();s.pu(s.po()/x);}
else s.pu(stoi(x));
}
cout<<s.po()<<endl;
return 0;

\$ g++ -std=c++11 -Wall gt.cpp && ./a.out
2 3 4 5 - * 6 7 8 - - * + 9 +
-10

[ 打印 ]