前缀表达式求值

#include 
using namespace std;
stackst;
double yunsuan(double a,double b,string  c)
{
    if(c=="+")
    {
        return a+b;

    }
    else if(c=="-")
    {
        return a-b;
    }
    else if(c=="*")
    {
        return a*b;
    }
    else
    {
        return a*1.0/b;
    }

}

int main()
{
    string s[31];
    int i=0;
    double a,b;
    int flag=0;
    while(cin>>s[i])
    {
        i++;
    }
    for(int j=i-1; j>=0; --j)
    {
        if(s[j]=="+"||s[j]=="-"||s[j]=="*"||s[j]=="/")//遇到符号从栈中弹出两个个值
        {
            int f1=0,f2=0;
            if(!st.empty())
            {
                f1=1;
                a=st.top();
                st.pop();
            }
            if(!st.empty())
            {
                f2=1;
                b=st.top();
                st.pop();
            }
            if(f1==1&&f2==1)
            {
                if(s[j]=="/"&&b==0)
                {
                    cout<<"ERROR";
                    flag=1;
                    break;
                }
                else
                    st.push(yunsuan(a,b,s[j]));
            }
            else
            {
                cout<<"ERROR";
                flag=1;
                break;
            }

        }
        else  //如果是操作数就转换成数压栈
        {
            st.push(atof(s[j].c_str()));
        }

    }
    if(flag==0)
        printf("%.1f",st.top());

    return 0;
}

没什么难度成功ac 跟后缀表达式差不多 遇到符号从栈中弹出2个元素 遇到操作数压栈

主要是要注意异常退出比如栈中拿不出两个元素或者除法遇到除以0的情况

然后要学会atof和atoi的使用  字符出转整型和实型

你可能感兴趣的:(前缀表达式求值)