c++中缀表达式转后缀表达式求值


c++中缀表达式转后缀表达式求值

#include<iostream>
#include<stack>
#include<string>
using namespace std;

string s;
stack<double> num;//操作数
stack<char> op;//操作符

int level(char c)
{
 if(c=='+'||c=='-') return 1;
 else if(c=='*'||c=='/') return 2;
 else if(c=='('||c==')') return 3;
 else return 0;
}
bool isSuper(char c1,char c2)//判断第二个操作优先级是否比第一个低
{
 if(level(c2)<=level(c1)) return true;
 else return false;
}

double cal(double left,double right,char op)
{
    if(op=='+') return left + right;
    if(op=='-') return left - right;
    if(op=='*') return left * right;
    if(op=='/') return left / right;
    
}

int main()
{
 cin>>s;
 for(int i = 0;i<s.length();i++)
 {
     
  switch(s[i])
  {
   case '-':case '*':case '/':
   case '+':{
    if(op.size()==0) op.push(s[i]);//如果当前操作符为空,直接入栈
    else{//将该运算符之前优先级高的运算操作都计算完
     while(op.size()>0 && isSuper(op.top(),s[i]) &&op.top()!='(')
     {
      double right = num.top();num.pop();//弹出右操作数进行运算
      double left = num.top();num.pop();//弹出左操作数进行运算
      double res = cal(left,right,op.top());//计算完将答案压入栈中
      op.pop();//弹出计算过的操作符
      num.push(res);
     }
     op.push(s[i]);//计算完前面优先级高的运算操作后将该运算符压入栈中
    }
    break;
   }
   case '(':op.push(s[i]);break;
   case ')':{
       while(op.size()>0&&op.top()!='(')
       //将最近的一个左括号到这个右括号之间的操作全部进行运算
       {
           double right = num.top();num.pop();
           double left = num.top();num.pop();
           double res = cal(left,right,op.top());op.pop();
           num.push(res);
       }
       op.pop();//弹出左括号
       break;
   }
   default:num.push(double(s[i]-48));break;
  }
 }
 
 while(op.size()>0)
 {
     double right = num.top();num.pop();
     double left = num.top();num.pop();
     double res = cal(left,right,op.top());op.pop();
     cout<<"left\t"<<left<<" right\t"<<right<<" cal\t"<<cal<<endl;
     num.push(res);
 }
 cout<<num.top()<<endl;
 return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Anonymous&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值