中缀表达式求值

来源:互联网 发布:王宏安 软件所 编辑:程序博客网 时间:2024/06/06 18:38

中缀表达式用于计算一个表达式,比如计算器 就是这样实现的

这儿是用栈的数据结构来实现的。首先输入一个字符串,表示一个表达式,然后用一个栈存储数字,另外一个栈存储符号

如果当前运算符优先级比栈顶元素优先级高,则入栈,若当前运算符优先级小于等于栈顶运算符优先级,则从数字栈中弹出两个元素,从符号栈中弹出一个符号,计算结果入栈(数字栈);

代码如下:

#include<iostream>

using namespace std;
#include<cstring>
#include<stack>
#include<cmath>
int judge(char x,char popx);
int func(int x,char str,int y);
int main()
{
int w;
cin>>w ;
while(w--)
{
stack<int>a;
stack<char>str;
int i,n;
char s[2000];
str.push('#');                                    //判断栈空的条件
cin>>s; 
for(i=0;i<strlen(s);)
{
if(s[i]-'0'>=0&&s[i]-'0'<=9)
{
int m[20],j;
for(j=i;s[j]-'0'>=0&&s[j]-'0'<=9;j++)   //计算数字的时候,因为数字可能大于10,所以这儿要专门计算
m[j-i]=s[j]-'0';
int sum=0;
for(int k=j-i-1;k>=0;k--)
sum+=m[k]*pow(10,j-i-k-1);
a.push(sum);
i=j;
}
else
{
if(judge(str.top(),s[i])==2)  //入栈 
{
str.push(s[i]);
i++;
}
else
if(judge(str.top(),s[i])==1)   //出栈先算
{
int numb1=a.top();
a.pop();
int numb2=a.top();
a.pop();
a.push(func(numb2,str.top(),numb1));
str.pop();

else
if(judge(str.top(),s[i]==3))   //括号 
{
str.pop();
i++;
}

}
while(true)
{
if(str.top()=='#')
{
cout<<a.top()<<endl;
a.pop();
break;
}
else
{
int numb5=a.top();
a.pop();
int numb6=a.top();
a.pop();
a.push(func(numb6,str.top(),numb5));
str.pop();
}
}
}
}
int judge(char popx,char x)              //确定优先级
{
if(popx=='*'||popx=='/')
{
if(x=='(')
return 2;   //直接入栈 
else
if(x=='+'||x=='-'||x==')'||x=='*'||x=='/')// 出栈先算 
return 1;      
}
else
if(popx=='+'||popx=='-')
{
if(x=='*'||x=='/'||x=='(')  //直接入栈 
return 2; 
else
if(x=='+'||x=='-'||x==')')
return 1; 
}
else
if((popx=='('&&x!=')')||popx=='#')
return 2;    //直接入栈
else
if(popx=='('&&x==')')
return 3;

}
int func(int x,char str,int y)            //计算值
{
if(str=='+')
return x+y;
if(str=='-')
return x-y;
if(str=='*')
return x*y;
if(str=='/')
return x/y;
}
1 0
原创粉丝点击