求前缀表达式的值

#include<iostream>
#include<algorithm>
#include<string>
#include<stack>
#include<stdlib.h> 
using namespace std;

stack<double>st;

int main()
{
    string str[100]; int n = 0;
//在求前缀或者后缀的时候,从前到后读入数据,前缀的话倒着读出数据,从右往左看,有数入栈,有运算符取栈顶两个,运算完入栈
    while (cin >> str[n++]) {}
    for (int i = n - 1; i >= 0; i--)
    {
        if (str[i].size() == 1 && (str[i] == "+" || str[i] == "-" || str[i] == "*" || str[i] == "/"))
        {
            double t1, t2;
            if (st.size() < 2) {
                cout << "ERROR" << endl;
                exit(0);
            }
            else
            {
                t1 = st.top(); st.pop();
                t2 = st.top(); st.pop();
            }
            switch (str[i][0])
            {
            case '+':
                st.push(t2 + t1);
                break;
            case '-':
                st.push(t1 - t2);
                break;
            case '*':
                st.push(t1 * t2);
                break;
            case '/':
//得分点,注意除数不能为0
                if (t2 == 0) {
                    cout << "ERROR" << endl;
                    exit(0);
                }
                st.push(t1 / t2);
                break;
            }
        }
        else {
//将字符串转变为浮点数,引入头文件stdlib.h
            double x = atof(str[i].c_str());
            st.push(x);
        }
    }
    printf("%.1f", st.top());
    return 0;
}

 

posted @ 2024-01-22 20:03  敲代码的6  阅读(21)  评论(0)    收藏  举报