字符串表达式求值

3+5*(4+8)/2   是一个字符串

 

 

// 感谢网友nasi00(莫傲·逍遥)提供代码

#include   <iostream>  
  using   namespace   std;  
   
  #include   <stack>  
  #include   <string>  
  #include   <cstdlib>  
   
  void   init(string&   s)  
  {  
  getline(cin,s);  
  s+="@";  
  }  
   
  bool   is_optr(char   c)  
  {  
  string   optr_list("+-*/()@");  
  for(int   i=0;i<optr_list.size();i++)  
  if(c==optr_list[i])  
  return   true;  
  return   false;  
  }  
   
  char   first(char   op1,   char   op2)  
  {  
  string   tab[7];  
  tab[0]=">><<<>>";  
  tab[1]=">><<<>>";  
  tab[2]=">>>><>>";  
  tab[3]=">>>><>>";  
  tab[4]="<<<<<=E";  
  tab[5]=">>>>E>>";  
  tab[6]="<<<<<E=";  
  string   optr_list("+-*/()@");  
   
  int   op1_loc,   op2_loc;  
   
  for(op1_loc=0;op1_loc<optr_list.size();op1_loc++)  
  if(optr_list[op1_loc]==op1)  
  break;  
  for(op2_loc=0;op2_loc<optr_list.size();op2_loc++)  
  if(optr_list[op2_loc]==op2)  
  break;  
   
  return   tab[op1_loc][op2_loc];  
  }  
   
  double   operate(double   x,   char   op,   double   y)  
  {  
  switch(op)   {  
  case   '+':  
  return   x+y;  
  break;  
  case   '-':  
  return   x-y;  
  break;  
  case   '*':  
  return   x*y;  
  break;  
  case   '/':  
  return   x/y;  
  break;  
  }  
  return   -1;  
  }  
   
  double   calc(string&   s)  
  {  
  stack<char>   optr;  
  optr.push('@');  
  stack<double>   opnd;  
   
  char   c=s[0];  
  s.erase(0,1);  
   
  while(   c!='@'   ||   optr.top()!='@'   )   {  
  if(   !is_optr(c)   )   {  
  string   num;  
   
  num.insert(num.begin(),   c);  
  int   loc=0;  
  while(   !is_optr(s[loc])   )  
  loc++;  
   
  string   num2(s,0,loc);  
  num+=num2;  
  s.erase(0,loc);  
   
  double   x=atof(num.c_str());  
  opnd.push(x);  
  c=s[0];  
  s.erase(0,1);  
  }  
  else   {  
  switch(   first(optr.top(),   c)   )   {  
  case   '<':  
  optr.push(c);  
  c=s[0];  
  s.erase(0,1);  
  break;  
  case   '=':  
  optr.pop();  
  c=s[0];  
  s.erase(0,1);  
  break;  
  case   '>':  
  char   op;  
  op=optr.top();  
  optr.pop();  
   
  double   a,b;  
  a=opnd.top();  
  opnd.pop();  
  b=opnd.top();  
  opnd.pop();  
   
  double   res;  
  res=operate(b,op,a);  
  opnd.push(res);  
   
  break;  
  }  
  }  
  }  
   
  return   opnd.top();  
  }  
   
  int   main()  
  {  
  string   exp;  
  double   ans;  
   
  init(exp);  
  ans=calc(exp);  
  cout<<ans<<endl;  
   
  return   0;  
  }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值