怎么去计算一个表达式
这是一个有用的中缀表达式转换成后缀表达式的程序。关键是转换之后,我应该怎么利用我转换出来的后缀表达式去计算一个式子?有帮我修改,加点东西进去的吗?
#include<iostream.h>
const maxsize=1000;
char s1[maxsize],s2[maxsize],s3[maxsize]; //分别存放中,后缀表达式
class seqstack //定义顺序栈
{
public:
char stack[maxsize];
int top;
void inistack() //栈的初始化
{
top=0;
}
void push(char x) //进栈
{
top++;
stack[top]=x;
}
void pop() //退栈
{
top--;
}
char gettop() //取栈顶元素
{
return stack[top];
}
bool empty() //判栈空
{
if(top==0)
return true;
else
return false;
}
int oper(char op) //返回运算符的优先级
{
switch(op)
{
case '+':case '-':return 1;
case '*':case '/':return 2;
case '(':return 0;
default:return 0;
}
}
void change() //中缀转换成等价的后缀表达式
{
char y,ch;
int top=0;
inistack();
push('@');
int i=0,j=0;
ch=s1[i];
while(ch!='@')
{
if(ch==' ')
ch=s1[++i];
else if(ch=='(') //遇左括号进栈
{
push(ch);
ch=s1[++i];
}
else if(ch==')') //遇右括号退栈,直到遇到左括号
{
y=gettop();
while(y!='(')
{
s2[j++]=y;
s2[j++]=' ';
pop();
y=gettop();
}
pop();
ch=s1[++i];
}
else if((ch=='+')||(ch=='-')||(ch=='*')||(ch=='/'))
{
y=gettop();
if(oper(ch)>oper(y))
{
push(ch);
ch=s1[++i];
}
else
{
y=gettop();
s2[j++]=y;
s2[j++]=' ';
pop();
}
}
else
{
while(((ch>='0')&&(ch<='9'))||(ch=='.'))
{
s2[j++]=ch;
ch=s1[++i];
}
s2[j++]=' ';
}
}
y=gettop();
while(y!='@')
{
s2[j++]=y;
s2[j++]=' ';
pop();
y=gettop();
}
s2[j]='@';
}
};
void main()
{
seqstack s;
char ch;
int i=0;
int m[100];
cout<<"请输入中缀表达式(以'@'结尾):";
cin>>ch;
while(ch!='@')
{
s1[i++]=ch;
cin>>ch;
}
s1[i]='@';
cout<<"中缀表达式为:";
for(int j=0;j<i;j++)
cout<<s1[j];
cout<<endl;
s.change();
cout<<"后缀表达式为:";
j=0;
while(s2[j]!='@')
{
cout<<s2[j];
j++;
}
cout<<endl;
}