对于运算表达式的运算优先级的解决方法(不带括号)

#include<iostream>
#include<cstring>
#include<iomanip>
#include<string>
#include<stack>
using namespace std;
char a[6];
stack<int>Num;
stack<char>Operator;
int main()
{
    int n;
    cin>>n;
    int t=n;
    while(t--)
    {
        while(!Num.empty())Num.pop();
        while(!Operator.empty())Operator.pop();
        int t1=1;
        for(int i=1; i<=n; i++)
        {
            cin>>a[i];
            if(i==1)
            {
                Num.push(a[i]-'0');
            }
            else
            {
                if(t1%2==0)
                {
                    Operator.push(a[i]);
                }
                else
                {
                    Num.push(a[i]-'0');
                    if(Operator.top()=='*')
                    {
                        int t1=Num.top();
                        Num.pop();
                        int t2=Num.top();
                        Num.pop();
                        Num.push(t1*t2);
                        Operator.pop();
                    }
                    else if(Operator.top()=='/')
                    {
                        int t1=Num.top();
                        Num.pop();
                        int t2=Num.top();
                        Num.pop();
                        Num.push(t2/t1);
                        Operator.pop();
                    }
                    else if(Operator.top()=='%')
                    {
                        int t1=Num.top();
                        Num.pop();
                        int t2=Num.top();
                        Num.pop();
                        Num.push(t2%t1);
                        Operator.pop();
                    }
                }
            }
            t1++;
        }
        int e=Num.top();
        int flag=1;
        int sum=0;
        while(!Operator.empty())
        {
            flag=0;
            char temp=Operator.top();
            Operator.pop();
            int t1=Num.top();
            Num.pop();
            int t2=Num.top();
            Num.pop();
            if(temp=='+')
            {
                Num.push(t1+t2);
            }
            else if(temp=='-')
            {
                Num.push(t2-t1);
            }
            sum=Num.top();
        }
        if(flag==0)
            cout<<sum<<endl;
        else
        {


            cout<<e<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/let_life_stop/article/details/80863085