输入一带括号的四则运算算术表达式(以#结束),求该表达式的值,并将其输出。
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class Calculator{
private:
string Polish;
long int result;
public:
long int& getResult(string exp) {
Polish.clear();
stack<char> s1,s2;
s1.push('#');
char temp;
for(int i=0; i<exp.length(); i++)
{
if (exp[i] >=48&& exp[i] <=57) {s2.push(exp[i]);}
else if (exp[i]>=42)
{
s2.push('#');
temp = s1.top();
if(temp == '#'||(temp == '+' || temp == '-')&&(exp[i] == '*' ||exp[i] == '/'))
{s1.push(exp[i]);}
else {
while (!(temp=='#'||temp == '(' || (temp == '+' || temp == '-') && (exp[i] == '*' ||exp[i] == '/')))
{
s2.push(temp);
s1.pop();
temp = s1.top();
}
s1.push(exp[i]);
}
}
else if(exp[i]>39)
{
if(exp[i] ==40)
{s1.push(exp[i]);}
else {
temp = s1.top();
while (temp !=40 )
{
s2.push(temp);
s1.pop();
temp = s1.top();
}
s1.pop();
}
}
}
while(s1.top()!='#')
{
s2.push(s1.top());
s1.pop();
}
for(;s2.size()>=1;)
{
Polish.push_back(s2.top());
s2.pop();
}
long int temp2,temp3,temp1=0;
stack<long int> s3;
bool sign =0;
for(int i = Polish.length()-1; i >= 0; i--)
{
if(Polish[i] >= 48&& Polish[i] <=57)
{
temp1 = temp1*10 + Polish[i]-'0';
sign = 1;
}
if((Polish[i] == '#'||(Polish[i]<48&&Polish[i]>41))&&(sign == 1)||(i == 0&&sign == 1))
{
if(sign == 1){
s3.push(temp1);
temp1 = 0;
sign = 0;
}}
if(Polish[i]>41&&Polish[i]<48)
{
temp2 =s3.top();
s3.pop();
temp3 =s3.top();
s3.pop();
switch(Polish[i]) {
case '+': s3.push(temp3+temp2);break;
case '-': s3.push(temp3-temp2);break;
case '*': s3.push(temp3*temp2);break;
case '/': s3.push(temp3/temp2);break;
}
}
}
result = s3.top();
return result;
}
};
int main()
{
Calculator c;
char cc[20];
cin>>cc;
cout<<"计算结果是:"<<c.getResult(cc)<<endl;
return 0;
}