表达式求值——栈

题目描述

对于一个不存在括号的表达式进行计算

输入描述:

存在多种数据,每组数据一行,表达式不存在空格

输出描述:

输出结果
示例1

输入

复制
6/2+3+3*4

输出

复制

18

#include<iostream>
#include<stack>
#include<string>
using namespace std;
string s;
stack<int>op;//存储运算符的编号.0:= 1:+ 2:- 3:* 4:/
stack<double>in;
int mat[][5]
{
    1,0,0,0,0,
    1,0,0,0,0,
    1,0,0,0,0,
    1,1,1,0,0,
    1,1,1,0,0,
};


void get(bool &retop,int &retnum,int &i)
{
    if(s[i]>='0'&&s[i]<='9')
    {
        retop=false;
        double temp=s[i]-'0';
        for(i++;s[i]>='0'&&s[i]<='9';i++)
        {
             temp=temp*10+s[i]-'0';
        }
        retnum=temp;
    }
    else
    {
        retop=true;
        if(s[i]=='#')
            retnum=0;
        else if(s[i]=='+')
            retnum=1;
        else if(s[i]=='-')
            retnum=2;
        else if(s[i]=='*')
            retnum=3;
        else if(s[i]=='/')
            retnum=4;
        i++;
    }
}
int main()
{
   
    while(cin>>s)
    {
         bool retop;//返回当前字符是否是运算符,是true 否false;
         int retnum;//如果是运算符返回运算符的编号,否则返回运算数
         int i;//遍历字符串的下标
         s='#'+s+'#';
         while(!op.empty())op.pop();
         while(!in.empty())in.pop();
        while(true)
     {
        get(retop,retnum,i);
        if(retop==false)
        {
            in.push((double)retnum);
        }//是数字
        else
        {
            double result;
            if(op.empty()||mat[retnum][op.top()]==1)
            {
                op.push(retnum);
            }
            else
            {
                while(mat[retnum][op.top()]==0)
                {
                    double a=in.top();
                    in.pop();
                    double b=in.top();
                    in.pop();
                    int c=op.top();
                    op.pop();
                    if(c==1)
                        result=a+b;
                    if(c==2)
                        result=b-a;
                    if(c==3)
                        result=a*b;
                    if(c==4)
                        result=b/a;
                    in.push(result);
                }
                op.push(retnum);
            }
        }

        if(op.size()==2&&op.top()==0)
            break;
      }

        cout<<in.top()<<endl;
    }
    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_38030194/article/details/80861299