中缀转后缀同时求值

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

边转换边求值,一趟完成


#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 ();
}



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值