这道题,我的思路是先将中缀表达式转换为后缀表达式,再用普通计算后缀表达式的方法来做就可以了
代码:
#include<bits/stdc++.h>
using namespace std;
stack<int> a;
int ys()
{
int n=a.top();
a.pop();
return n;
}
string qth(string n)//中缀表达式转后缀表达式
{
int z=0;
stack<char> b;
string t;
for(int i=0;i<n.size();i++)
{
if(n[i]>='0'&&n[i]<='9')
{
while(n[i]>='0'&&n[i]<='9')
{
t=t+n[i];
i++;
}
t=t+" ";
}
if(n[i]=='('||n[i]=='+'||n[i]=='-')
{
if(n[i]=='(')
{
z++;
}
while(n[i]!='('&&!b.empty()&&(b.top()=='*'||b.top()=='/'||b.top()=='+'||b.top()=='-'))
{
t=t+b.top();
b.pop();
}
b.push(n[i]);
}
else
if(n[i]=='*'||n[i]=='/')
{
while(!b.empty()&&(b.top()=='*'||b.top()=='/'))
{
t=t+b.top();
b.pop();
}
b.push(n[i]);
}
else
if(n[i]==')')//判断是否有多余的括号
{
if(z>0)
{
z--;
}
else
{
cout<<"NO"<<endl;
exit(0);
}
while(b.top()!='(')
{
t=t+b.top();
b.pop();
}
b.pop();
}
}
while(!b.empty())
{
t=t+b.top();
b.pop();
}
return t;
}
void pd(string t)//判断是否有重复的符号
{
for(int i=0;i<t.size()-1;i++)
{
if((t[i]=='+'||t[i]=='-'||t[i]=='*'||t[i]=='/')&&(t[i+1]=='+'||t[i+1]=='-'||t[i+1]=='*'||t[i+1]=='/'))
{
cout<<"NO"<<endl;
exit(0);
}
}
}
int main()
{
string n;
cin>>n;
pd(n);
n=n.substr(0,n.size()-1);
n=qth(n);
int t=0,z;
for(int i=0;i<n.size();i++)//后缀表达式计算
{
if(n[i]>='0'&&n[i]<='9')
{
t=t*10+n[i]-'0';
continue;
}
if(n[i]==' ')
{
a.push(t);
t=0;
continue;
}
if(n[i]=='+')
{
z=ys();
a.push(ys()+z);
}
if(n[i]=='-')
{
z=ys();
a.push(ys()-z);
}
if(n[i]=='*')
{
z=ys();
a.push(ys()*z);
}
if(n[i]=='/')
{
z=ys();
if(z==0)
{
cout<<"NO"<<endl;
return 0;
}
a.push(ys()/z);
}
}
cout<<a.top();
return 0;
}
有点长,请见谅