//输入表达式,输出值! (中缀表达式)
//都单步还是想不通输入1 + 2 00的时候那个运算符栈为什么会输出是00,2
#include<iostream>
#include<cstdlib>
#include<stack>
using namespace std;
bool in_out(char in,char out)//true in
{
if(out=='(')
return true;
else if(out==')'&&in!='(')
return false;
else if(in=='('&&out!=')')
return true;
else if(in=='('&&out==')')
return false;
if((in=='+'||in=='-')&&(out=='*'||out=='/'))
{
return true;
}
return false;
}
int main()
{
cout<<"请输入中缀表达式,每个数字或字符用空格隔开"<<endl;
char op[100];
stack<char*> yunsuan;
stack<double> number;
while(cin>>op)
{
if(strcmp(op,"00")==0)
break;
if(op[0]!='+'&&op[0]!='-'&&op[0]!='*'&&op[0]!='/'&&op[0]!='('&&op[0]!=')')
{
number.push(atof(op));
continue;
}
if(yunsuan.empty())
{
yunsuan.push(op);
continue;
}
char in;
in=yunsuan.top()[0];
char out=op[0];
bool res=in_out(in,out);
if(res)
{
yunsuan.push(op);
continue;
}
while(!res)
{
if(in=='('&&out==')')
{
yunsuan.pop();////////
// res=true;
//continue;
break;
}
else
{
double n2=number.top();
number.pop();
double n1=number.top();
number.pop();
switch(out)
{
case '(':
break;
case ')':
break;
case '+':
number.push(n1+n2);
break;
case '-':
number.push(n1-n2);
break;
case '*':
number.push(n1*n2);
break;
case '/':
number.push(n1/n2);
break;
default:cout<<"error"<<endl;
}
yunsuan.pop();
//number.push();
in=yunsuan.top()[0];
res=in_out(in,out);
}
}
yunsuan.push((char*)(""+out));
}
while(!yunsuan.empty())
{
cout<<yunsuan.top()<<endl;
yunsuan.pop();
/*
char out=yunsuan.top()[0];
double n2=number.top();
number.pop();
double n1=number.top();
number.pop();
switch(out)
{
case '(':
break;
case ')':
break;
case '+':
number.push(n1+n2);
break;
case '-':
number.push(n1-n2);
break;
case '*':
number.push(n1*n2);
break;
case '/':
number.push(n1/n2);
break;
default:cout<<"error"<<endl;
}
yunsuan.pop();
*/
}
cout<<number.top()<<endl;
return 0;
}