用C++实现表达式求值

来源:互联网 发布:淘宝双十一红包攻略 编辑:程序博客网 时间:2024/06/05 19:45

算法思想:使用两个栈,分别用来存储数和运算符,使用一个字符串来接受所要进行运算的表达式,用字符串中的符号与存储符号的栈进行比较,如果外来的运算符优先级大于栈内的运算符,则将存储数的栈顶出栈与字符串的下一个字符进行运算。否则将其压栈。最后得到的将是一个只需进行最后一步运算的两个栈,最后进行运算,直到存储符号的栈为空为止。下面的未涉及(),推广一下即可

#include<iostream>#include<stack>#include<string>using namespace std;bool compare_fuhao(char c,stack<char> st2){if(c=='*'||c=='/')if(st2.top()=='*'||st2.top()=='/')return false;elsereturn true;return false;}int main(){stack<int> st1;stack<char> st2;string str;cout<<"请输入要计算的表达式:";cin>>str;int i=0;int x,y;char c;while(i<str.size()){if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/'){if(st2.size()!=0){ if(compare_fuhao(str[i],st2))//#号的优先级比别的符号的优先级都低。{x=st1.top();st1.pop();switch(str[i]){case '+':x=x+str[i+1]-'1'+1;break;case '-':x=x-str[i+1]-'1'+1;break;case '*':x=x*(str[i+1]-'1'+1);break;case '/':x=x/(str[i+1]-'1'+1);break;}st1.push(x);i++;}else{x=st1.top();st1.pop();y=st1.top();st1.pop();c=st2.top();st2.pop();switch(c){case '+':x=x+y;break;case '-':x=x-y;break;case '*':x=x*y;break;case '/':x=x/y;break;}st1.push(x);st2.push(str[i]);}}elsest2.push(str[i]);}elsest1.push(str[i]-'1'+1);i++;}i=0;int l=st2.size();while(i<l){x=st1.top();st1.pop();y=st1.top();st1.pop();c=st2.top();st2.pop();switch(c){case '+':x=y+x;break;case '-':x=y-x;break;case '*':x=x*y;break;case '/':x=y/x;break;}st1.push(x);i++;}cout<<"结果为:"<<st1.top()<<endl;system("pause");return 0;}


 

原创粉丝点击