中綴轉字尾同時求值
阿新 • • 發佈:2018-12-18
中綴轉字尾的同時進行求值
邊轉換邊求值,一趟完成
#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; else return 0; } int icp(char ks){ if(ks=='-'||ks=='+') return 1; else if(ks=='*'||ks=='/') return 3; else return 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 (); }