NYOJ35 Expression Evaluation (Dual Stack Method)

describe

The mdd of the ACM team wants to make a calculator, but what he wants to do is not only a calculator that calculates A+B, he wants to realize a calculator that can find its value by inputting any expression. Now please You help him implement this calculator.
For example, if you input: "1+2/4=", the program will output 1.50 (retain two decimal places for the result)

enter

The first line inputs an integer n, and there are n groups of test data (n<10).
Each set of test data has only one line, which is a character string with a length of no more than 1000, indicating this expression, and each expression ends with "=". This expression contains only the symbols +-*/ and parentheses. The parentheses can be nested. The data guarantees that no negative numbers will appear in the input operands.
The data guarantees that the divisor will not be 0

output

Each group outputs the operation result of this group of expressions, and the output result retains two decimal places.

sample input

2
1.000+2/4=
((1+2)*5+1)/4=

Sample output

1.50
4.00

ideas

The double stack method is a relatively simple expression evaluation method:

First you need two stacks, one to store numbers and the other to store symbols.
The specific method is:

  1. First push the left parenthesis onto the symbol stack and scan the string from left to right
  2. If you encounter a number 1~9or .use a string to store it
  3. When the encounter is not a number, it means that the symbol is currently encountered, the stored string is turned into a number, and then pushed into the number stack. Then judge what symbol is currently encountered. If it is addition and subtraction, then directly take two numbers from the symbol stack for calculation, and then push the result into the stack. If the multiplication and division symbol is encountered, then directly calculate all the numbers in the stack first. multiplication and division, then push the current symbol onto the stack
  4. If a closing parenthesis or an equal sign is encountered, the remaining symbols on the stack are calculated directly.
  5. The top of the stack in the final output number stack is the answer

code

#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
#include <sstream>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
#include <list>
using namespace std;
#define mem(a, b) memset(a, b, sizeof(a))
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define inf 0x3f3f3f3f
typedef long long ll;
const int N = 1000 + 20;
stack<char> st_ch;
stack<double> st_num;
void calc1()
{
    char ch = st_ch.top();
    while (ch != '(')
    {
        double num1 = st_num.top();
        st_num.pop();
        double num2 = st_num.top();
        st_num.pop();
        switch (ch)
        {
        case '+':
            num2 += num1;
            break;
        case '-':
            num2 -= num1;
            break;
        case '*':
            num2 *= num1;
            break;
        case '/':
            num2 /= num1;
            break;
        }
        st_num.push(num2);
        st_ch.pop();
        ch = st_ch.top();
    }
}
void calc2()
{
    char ch = st_ch.top();
    while (ch == '*' || ch == '/')
    {
        double num1 = st_num.top();
        st_num.pop();
        double num2 = st_num.top();
        st_num.pop();
        switch (ch)
        {
        case '*':
            num2 *= num1;
            break;
        case '/':
            num2 /= num1;
            break;
        }
        st_num.push(num2);
        st_ch.pop();
        ch = st_ch.top();
    }
}
int main()
{
    //freopen("in.txt", "r", stdin);
    string str;
    int t;
    cin >> t;
    while (t--)
    {
        cin >> str;
        int len = str.size();
        st_ch.push('(');
        string str_num = "";
        for (int i = 0; i < len; i++)
        {
            if (isdigit(str[i]) || str[i] == '.')
            {
                str_num += str[i];
                continue;
            }
            if (str_num != "")
            {
                double num = atof(str_num.c_str());
                st_num.push(num);
                str_num = "";
            }
            switch (str[i])
            {
            case '+':
            case '-':
                calc1();
                st_ch.push(str[i]);
                break;
            case '*':
            case '/':
                calc2();
                st_ch.push(str[i]);
                break;
            case '(':
                st_ch.push('(');
                break;
            case ')':
            case '=':
                calc1();
                st_ch.pop();
                break;
            }
        }
        printf("%.2lf\n", st_num.top());
        st_num.pop();
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325854379&siteId=291194637