表达式求值问题。。中缀转化为后缀。。。
#include<iostream>
#include<string.h>
#include<string>
#include<cctype>
#include<cstdio>
#include<stack>
#include<cstdlib>
using namespace std;
stack<char> fu;
stack<float>shu;
stack<char> Q;
float cal(float a,float b,char c)
{ switch(c)
{ case'+':return a+b;
case'-': return a-b;
case '*':return a*b;
case '/':return a/b;
}
}
int ran(char a)
{ if(a=='#') return 0;
if(a=='('||a==')') return 1;
if(a=='+'||a=='-') return 2;
if(a=='*'||a=='/') return 3;
}
void doit()
{ float frist ,second, result;
char c;
second=shu.top();
shu.pop();
frist=shu.top();
shu.pop();
c=fu.top();
fu.pop();
result=cal(frist,second,c);
shu.push(result);
}
void sback(string str)
{
int m=str.size();
string shu1="";
bool flag(false);
fu.push('#');
for(int i=0;i<m-1;++i)
{ if(isdigit(str[i])||str[i]=='.') flag=true;
else flag=false;
if(flag) shu1+=str[i];
else
{
if(!shu1.empty())
{cout<<shu1;
float k=atof(shu1.data());
shu.push(k);
}
shu1="";
if(str[i]=='(') fu.push(str[i]);
else if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
{ int cmp=ran(str[i])-ran(fu.top());
if(cmp>0) fu.push(str[i]);
else
{ while(ran(str[i])-ran(fu.top())<=0)
{ cout<<fu.top();
doit();
}
fu.push(str[i]);
}
}
else if(str[i]==')')
{
while(fu.top()!='(')
{ cout<<fu.top();
doit();
}
fu.pop();
}
}
}
if(flag)
{
if(!shu1.empty())
{
cout<<shu1;
float k=atof(shu1.data());
shu.push(k);
}
}
while(fu.top()!='#')
{ cout<<fu.top();
doit();
}
cout<<"="<<endl;
printf("%.2f\n",shu.top());
shu.pop();
fu.pop();
}
int main()
{ int n;
cin>>n;
while(n--)
{ string s;
cin>>s;
//sfront(s);
sback(s);
cout<<endl;
} return 0;
}