您的位置:首页 > 其它

中缀转后缀同时求值

2016-03-19 23:04 316 查看
中缀转后缀的同时进行求值

边转换边求值,一趟完成

#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 ();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: