表达式求值

来源:互联网 发布:打印软件下载 编辑:程序博客网 时间:2024/06/05 18:17

方法一:

// exam1.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <stack>using namespace std;int priority(char op){switch(op){case '(':return 1;case '+':case '-':return 2;case '*':case '/':return 3;case ')':return 4;case '#':return 5;}}bool cmp_lg(char op1,char op2){int proi1=priority(op1);int proi2=priority(op2);if(proi1>=proi2){return true;}else{return false;}}int cal_func(char op,int num1,int num2){switch(op){case '+':return num1+num2;case '-':return num1-num2;case '*':return num1*num2;case '/':return num1/num2;default:return num1+num2;}}void cal(void){cout<<"Please enter the formula whose end is '#'..."<<endl;char ch;stack<int> num;stack<char> op;while(1){cin>>ch;if(ch=='#'){break;}if(ch>='0' && ch<='9'){num.push(ch-'0');}else{if(op.empty()){op.push(ch);}else{char op1,op2;op1=op.top();op2=ch;if(ch=='('){op.push(ch);}else if(cmp_lg(op1,op2)){int result,num1,num2;num1=num.top();num.pop();num2=num.top();num.pop();result=cal_func(op1,num1,num2);num.push(result);op.pop();op.push(op2);}else{if(ch==')'){int result;int num1,num2;char op0;num1=num.top();num.pop();num2=num.top();num.pop();op0=op.top();op.pop();op.pop();result=cal_func(op0,num1,num2);num.push(result);}else{op.push(ch);}}}}}while(!num.empty() && !op.empty()){int result;int num1,num2;char op0;num1=num.top();num.pop();num2=num.top();num.pop();op0=op.top();op.pop();result=cal_func(op0,num1,num2);num.push(result);}cout<<"The result is "<<num.top()<<"."<<endl;}int main(void){cal();system("pause");return 0;}

方法二:

将()内看成是一个数,使用递归算法进行解决

上代码

#include "stdafx.h"#include <iostream>#include <stack>using namespace std;void calculate(stack<int> &num,stack<char> &op){int b=num.top();num.pop();int a=num.top();num.pop();char sym=op.top();op.pop();switch (sym){case '+':num.push(a+b);break;case '-':num.push(a-b);break;case '*':num.push(a*b);break;case '/':num.push(a/b);break;default:;}}int cal(char* s,int len){char*p=s;stack<int> num;stack<char> op;while(len!=0){if(*p=='('){int cnt=1;char* cur=p+1;while(cnt!=0){if(*cur==')'){cnt--;}else if(*cur=='('){cnt++;}else{}cur++;}int tmp=cal(p+1,cur-p-2);len=len-(cur-p-1);num.push(tmp);p=cur-1;}else if(*p<='9' && *p>='0'){num.push(*p-'0');}else if(op.empty()){op.push(*p);}else if(op.top()=='*' || op.top()=='/'){calculate(num,op);op.push(*p);}else{if(*p=='*' || *p=='/'){op.push(*p);}else{calculate(num,op);op.push(*p);}}p++;len--;}while(!op.empty()){calculate(num,op);}return num.top();}int main(){char* s="1+(4-3)*5/5-3+4";int result=cal(s,strlen(s));cout<<result<<endl; system("pause"); return 0;}



0 0