#include <iostream>
#include <string>
#include<stack>
using namespace std;
int Comp(char str1, char str2)
{
switch (str1)
{
case '+': case '-': if (str2 == '(' || str2 == '#') return 1; else return -1;
break;
case '*': case '/': if (str2 == '*' || str2 == '/') return -1; else return 1;
break;
case '(': return 1; break;
case ')': if (str2 == '(') return 0; else return -1;
break;
case '#': if (str2 == '#') return 0; else return -1;
break;
default: break;
}
}
void Compute(string ch)
{
string result;
stack<char> OPTR;
ch=ch+'#';
OPTR.push('#');
for (int i = 0;ch[i]!='\0';)
{
if(ch[i]>='0'&&ch[i]<='9')
{
result=result+ch[i++];
}
else
{
int k;
k=Comp(ch[i],OPTR.top());
if(k==1)
{
OPTR.push(ch[i++]);
}
else if(k==-1)
{
char op=OPTR.top();
OPTR.pop();
result=result+op;
}
else
{
OPTR.pop();
i++;
}
}
}
cout<<result<<endl;
}
int main( )
{
string str;
cout << "请输入一个表达式:";
cin >> str;
cout << "表达式的值是:";
Compute(str);
return 0;
}
03-14
1365
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-22
2861
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-17
8783
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-19
2512
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)