中缀转后缀同时求值

来源:互联网 发布:25颗摇头矩阵灯厂家 编辑:程序博客网 时间:2024/05/21 09:01

中缀转后缀的同时进行求值

边转换边求值,一趟完成


#include<iostream>#include<stack>#include<string>using namespace std;//中缀转后缀并求值,只有加减乘除,输入形如:12.7-2*(72.2+4*(2.2+2.8))/2+100#int isp(char ks){if(ks=='-'||ks=='+')return 2;else if(ks=='*'||ks=='/')return 4;elsereturn 0;}int icp(char ks){if(ks=='-'||ks=='+')return 1;else if(ks=='*'||ks=='/')return 3;elsereturn 5;}void calculate(stack<double>& nStack,char c){double dou2=nStack.top(); nStack.pop();double dou1=nStack.top(); nStack.pop();if(c=='-'){nStack.push(dou1-dou2);}if(c=='+'){nStack.push(dou1+dou2);}if(c=='*'){nStack.push(dou1*dou2);}if(c=='/'){nStack.push(dou1/dou2);}}void solve (){char ch,  y ;stack <char> s ; stack <double> operandStack ;string operandStr;double operand;bool construcOperand=false;s.push ('#');     while (cin.get ( ch ) , ch != '#'){   if (isdigit ( ch )||ch=='.') {    if(construcOperand==false){cout<<" ";construcOperand=true;}    operandStr+=ch;cout << ch;    }        else{if(construcOperand==true){operand=atof(operandStr.c_str());operandStack.push(operand);construcOperand=false;operandStr="";}if (ch ==')')for (y=s.top(),s.pop();  y!= '(';  y=s.top( ),s.pop()){cout <<" "<< y ;calculate(operandStack,y);}else {for (y =s.top(),s.pop(); isp (y) > icp (ch); y=s.top(),s.pop()){cout<<" "<<y ;calculate(operandStack,y);}s.push (y) ; s.push (ch);     } }      }  if(construcOperand==true){  operand=atof(operandStr.c_str());  operandStack.push(operand);  construcOperand=false;  operandStr="";  }  while (!s.empty()&&s.top()!='#')  {  y = s.top();s.pop() ;  cout <<" "<<y ;   calculate(operandStack,y);  }  cout<<endl<<"计算结果是: "<<operandStack.top()<<endl;}int main(){solve ();}



0 0