中缀表达式转成后缀表达式
1+2+3*(3+4)中缀表达式
1 2 + 3 3 4 + * + 后缀表达式
#include<iostream>
#include<stack>
using namespace std;
int K(char c)//自己定义运算符级别
{
if (c == '#' || c == '(') return 0;
if (c == '-' || c == '+')return 1;
if (c == '/' || c == '*')return 2;
return 3;
}
string Convert(string a)//后缀表达式转换
{
string b;
a += '#';
stack<char> s;
s.push('#');
for (int i = 0; i < a.size() - 1; i++)
{
if (a[i]=='.'||(a[i] >= '0' && a[i] <= '9'))
{
b += a[i];
if( (a[i + 1] < '0' || a[i + 1]>'9')&&a[i+1]!='.')
b = b + " ";
}
else
{
if(a[i]=='(') s.push(a[i]);
else if (K(a[i]) <= K(s.top()))
{
while (K(a[i]) <= K(s.top()))
{
b += s.top();
s.pop();
// s.push(a[i]);
} s.push(a[i]);
}
else if (a[i] == ')')
{
while (s.top() != '(')
{
b += s.top();
s.pop();
}s.pop();
}
else s.push(a[i]);
}
}
while (s.top() != '#')
{
b += s.top();
s.pop();
}
return b;
}
double out(string b)//通过后缀表达式计算数据返回
{
double sum = 0,t1,t2,k=0,k1=0;
bool q = 1;
stack<double> s;
for (int i = 0; i < b.size(); i++)
{
if (b[i] == ' ')
{
s.push(k);
q = 1;
k = 0;
k1 = 0;
}
else if (b[i] == '.')
{
q = 0;
k1 = 10;
}
else if (b[i] < '0' || b[i]>'9')
{
t1 = s.top();
s.pop();
t2 = s.top();
s.pop();
if (b[i] == '+') sum = t2 + t1;
if (b[i] == '-') sum = t2 - t1;
if (b[i] == '*') sum = t2 * t1;
if (b[i] == '/') sum = t2 / t1;
s.push(sum);
}
else if(q)
{
k = k * 10 + b[i] - '0';
}
else
{
k = k + (b[i] - '0') / k1;
k1 *= 10;
}
}
return s.top();
}
int main()
{
string a;
cin >> a;
a = Convert(a);
cout<<out(a)<<endl;
return 0;
}
简单用了个栈代码健壮性不足只能计算正确的表达式