#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;
}
首先设立两个栈,一个存放数字,一个存放字符串(加减乘除乘方),然后分别入栈。
当即将入栈的符号的运算级大于栈顶的运算级,直接入栈。如果即将入栈的符号运算级小于等于栈顶,则先把栈内的式子先出栈计算,注意的是数字字符转换成数字。