7-11 suffix evaluation (25 points)

We humans are accustomed to writing "infix", such as 3 + 5* 2, its value is 13. (ps Why are humans accustomed to the infix style? Is it because the infix style is
easier to use than the suffix style?) And computers are more accustomed to the "suffix style" (also called "Reverse Polish Notation"). The suffix formula corresponding to the above infix formula is: 3 5 2 * +
Now, please evaluate the input suffix formula.

Input format:
Enter a suffix in one line, separate the operand and the operator with a space, the length of the operand does not exceed 6 digits, and there are only four types of operators: +-* /.

Output format:
output the suffix value in one line, with one decimal place.

Input sample:

3 5.4 2.2 * +

Sample output:

14.9

After going over it again, the difficulty of this question is reduced, and the step of converting the infix to the suffix is ​​omitted, and the suffix can be directly calculated. Using the string intercept function, the number is converted into a number and put on the stack (floating point number, because there are decimals), it is the operator to let the stack top and sub-stack top elements pop out of the stack to participate in the operation, note-and / operation is the second time When popping out of the stack, do the subtracted (or dividend), pay attention to exit directly when the divisor is 0 (to prevent disgusting test points), and finally output the top element of the stack to be the result
The other questions seem to have been blogged, so I won’t write O(∩_∩)O
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
    
    
    string s, ss;
    getline(cin, s);
    stack<double> st;
    double a, b;
    for (int i = 0; i < s.length();) {
    
    
        int j = i;
        while (j < s.length() && s[j] != ' ')
            j++;
        ss = s.substr(i, j - i);
        i += j - i + 1;
        if (ss == "+") {
    
    
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();
            st.push(a + b);
        } else if (ss == "-") {
    
    
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();
            st.push(b - a);
        } else if (ss == "*") {
    
    
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();
            st.push(a * b);
        } else if (ss == "/") {
    
    
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();
            if (a == 0)
                return 0;
            else
                st.push(b / a);
        } else {
    
    
            st.push(stod(ss));
        }
    }
    printf("%.1lf", st.top());
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45845039/article/details/112726849