新手用C++编写的用栈求解算数表达式的程序,望朋友帮忙看一下,多谢
#include<iostream>#include<cstring>
#include<string>
#include<stack>
#include<cmath>
#include<cstdlib>
#include<cctype>
using namespace std;
char OP[7]={'+','-','*','/','(',')','#'};
char Priority[7][7]={{'>','>','<','<','<','>','>'},{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=','@'},{'>','>','>','>','@','>','>'},
{'<','<','<','<','<','@','='}};
int Isoperator(char c)
{
for(int i=0;i!=7;++i)
if(c==OP[i]) return 1;
return 0;
}
char Precede(char c1,char c2)
{
int m,n;
for(int i=0;i!=7;i++)
{if(c1==OP[i]) m=i;
if(c2==OP[i]) n=i;}
return Priority[m][n];
}
float Operate (float a,char theta,float b)
{
switch (theta)
{
case '+':
return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':
if(b==0) cout<<"the number b divided is zero"<<endl;
else return a/b;
}
}
float EvaluateExpression(){
stack <char> OPTR;
OPTR.push('#');
stack <float> OPND;float sum;
char c;
cin>>c;
while(c!='#'||OPTR.top()!='#')
{
if(!Isoperator(c))
{
sum=0;
while(!Isoperator(c))
{
sum=10*sum+(c-'0');
cin>>c;
if(!Isoperator(c)) continue;//如果C还是数字的话,继续输入字符
else break;//否则退出循环
}
OPND.push(sum);//将数字输入的数字压入栈中
}
else
switch(Precede(OPTR.top(),c))
{
case '<':
OPTR.push(c);
cin>>c;
break;
case '=':
OPTR.pop();
cin>>c;
break;
case '>':
char theta=OPTR.top();
OPTR.pop();
float b=OPND.top();
OPTR.pop();
float a=OPND.top();
OPTR.pop();
OPND.push(Operate(a,theta,b));
break;
}
}
return OPND.top();
}
int main()
{
cout<<EvaluateExpression()<<endl;
return 0;
}