中缀表达式的计算

#include <errno.h>
#include<list>
#include<algorithm>
#include<cstdio>
#include<vector>
#include <iostream>
#include<string>
#include<stack>
#define INT_MAX (1<<30)
using namespace std;
int get(char ch){
  switch(ch){
    case '+':
    case '-':return 1;
    case '*':
    case '/':return 2;
    default:return 0;
  }
}
bool isLower(char s1,char s2){
  return get(s1)<get(s2); 
}
void change(const string& s,string & res){
 stack<char> s1,s2;
 s1.push('#');
 int i=0;
 while(i<s.length()){
  if(s[i]=='('){
   s1.push(s[i]);i++;
  }else if(s[i]==')'){
   while(s1.top()!='('){
    res+=s1.top();
    res+=' ';
    s1.pop();
   }
   s1.pop();
   i++;
  }else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
    while(get(s1.top())>=get(s[i])){
     res+=s1.top();s1.pop();
     res+=' ';
    }
    s1.push(s[i]);
    i++;
  }else{
    while(isdigit(s[i])||s[i]=='.'){
      res+=s[i];i++;
    }
    res+=' ';

  }
 }
 while(s1.top()!='#'){
  res+=s1.top();s1.pop();
    res+=' ';
 }

}

double value(string s2){
 stack<double> s;
 double x,y;
 int i=0;
 while(i<s2.length()){
   if(s2[i]==' ') {i++;continue;}
   switch(s2[i]){
     case '+':x=s.top();s.pop();x+=s.top();s.pop();++i;break;
     case '-':x=s.top();s.pop();x=s.top()-x;s.pop();++i;break;
     case '*':x=s.top();s.pop();x*=s.top();s.pop();++i;break;
     case '/':x=s.top();s.pop();x=s.top()/x;s.pop();++i;break;
     default:
     {
       x=0;
       while(isdigit(s2[i])){
        x=x*10+s2[i]-'0';
        i++;
       }
       if(s2[i]=='.'){
        double k=10.0;
        y=0;
        i++;
        while(isdigit(s2[i])){
         y+=((s2[i]-'0')/k);
         i++;
         k*=10;
        }
        x+=y;
       }
     }
   }
     s.push(x);
 }
  return s.top();
 
}
int main(){
 string res;
 change("3-2+25*2",res);
 cout<<value(res)<<endl;
 return 0;
 
}

只考虑加减乘除的版本,从中缀表达式转到后缀表达式:

void change(const string& s,string & res){
  stack<char> sta;
  int i=0;
  while(i<s.length()){
    if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
       while(!sta.empty()&&get(sta.top())>=get(s[i])){
         res+=sta.top();
         res+=' ';
         sta.pop();
       }
       sta.push(s[i]);
       i++;
    }else{
      while(isdigit(s[i])){
       res+=s[i];
       i++;
      }
      res+=' ';
    }
  }
  while(!sta.empty()){
   res+=sta.top();
   res+=' ';
   sta.pop();
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值