表达式求值(数据结构之栈)

 中缀表达式转成后缀表达式

1+2+3*(3+4)中缀表达式

1 2 + 3 3 4 + * +  后缀表达式

#include<iostream>
#include<stack>
using namespace std;
int K(char c)//自己定义运算符级别
{
    if (c == '#' || c == '(') return 0;
    if (c == '-' || c == '+')return 1;
    if (c == '/' || c == '*')return 2;
    return 3;
}
string Convert(string a)//后缀表达式转换
{
    string b;
    a += '#';
    stack<char> s;
    s.push('#');
    for (int i = 0; i < a.size() - 1; i++)
    {
        if (a[i]=='.'||(a[i] >= '0' && a[i] <= '9'))
        {
            b += a[i];
            if( (a[i + 1] < '0' || a[i + 1]>'9')&&a[i+1]!='.')
                b = b + " ";
        }
        else
        {
             if(a[i]=='(') s.push(a[i]);
             else if (K(a[i]) <= K(s.top()))
             {
                   while (K(a[i]) <= K(s.top()))
                   {
                       b += s.top();
                       s.pop();
                     //  s.push(a[i]);
                   }  s.push(a[i]);
              }
             else  if (a[i] == ')')
             {
                  while (s.top() != '(')
                  {
                      b += s.top();
                      s.pop();
                  }s.pop();
              }
             else s.push(a[i]);
            
        }
    }
    while (s.top() != '#')
    {
        b += s.top();
        s.pop();
    }
    return b;
}
double out(string b)//通过后缀表达式计算数据返回
{
    double sum = 0,t1,t2,k=0,k1=0;
    bool q = 1;
    stack<double> s;
    for (int i = 0; i < b.size(); i++)
    {      
       if (b[i] == ' ')
        {
            s.push(k);
            q = 1;
            k = 0;
            k1 = 0;
        }
       else if (b[i] == '.')
       {
           q = 0;
           k1 = 10;
       }
        else if (b[i] < '0' || b[i]>'9')
        {
            t1 = s.top();
            s.pop();
            t2 = s.top();
            s.pop();
            if (b[i] == '+') sum = t2 + t1;
            if (b[i] == '-') sum = t2 - t1;
            if (b[i] == '*') sum = t2 * t1;
            if (b[i] == '/') sum = t2 / t1;
            s.push(sum);

        }
        else if(q)
        {
            k = k * 10 + b[i] - '0';
        }
        else 
        {
           k = k + (b[i] - '0') / k1;
           k1 *= 10;
        }
    }
    return s.top();
}
int main()
{
    string a;
    cin >> a;
    a = Convert(a);
    cout<<out(a)<<endl;
    return 0;
}

 简单用了个栈代码健壮性不足只能计算正确的表达式

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DyingLive

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

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

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

打赏作者

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

抵扣说明:

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

余额充值