蓝桥杯的训练-表达式计算


#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <cmath>
#include <queue>

using namespace std;
char prior[7][7] =
{
    '>', '>', '<', '<', '<', '>', '>',
    '>', '>', '<', '<', '<', '>', '>',
    '>', '>', '>', '>', '<', '>', '>',
    '>', '>', '>', '>', '<', '>', '>',
    '<', '<', '<', '<', '<', '=', ' ',
    '>', '>', '>', '>', ' ', '>', '>',
    '<', '<', '<', '<', '<', ' ', '='
};
char OPSET[7] = { '+', '-', '*', '/', '(', ')', '\n' };

int In(char c)
{
    int i;
    for (i = 0; i < 7; i++)
        if (OPSET[i] == c) return true;
    return false;
}

int GetPos(char c)
{
    int i;
    for (i = 0; i < 7; i++)
        if (OPSET[i] == c) return i;
    return false;
}

int precede(char a, char b)
{
    return prior[GetPos(a)][GetPos(b)];
}

int Operate(int a, char theta, int b)
{
    switch (theta)
    {
    case '+':
        return a + b;
    case '-':
        return a - b;
    case '*':
        return a * b;
    case '/':
        return a / b;
    }
    return 0;
}

int main()
{
    stack<char> OPTR;
    stack<int> OPND;
    int a, b;
    char theta, c;
    OPTR.push('\n');
    c = getchar();
    while (c != '\n' || OPTR.top() != '\n')
        if (!In(c))
        {
            int sum = 0, i = 0;
            char s[20];
            s[i++]=c;
            c = getchar();
            while(!In(c))
                 s[i++]=c,c = getchar();
            OPND.push(atof(s));
        }
        else
            switch (precede(OPTR.top(), c))
            {
            case '<':
                OPTR.push(c);
                c = getchar();
                break;
            case '=':
                OPTR.pop();
                c = getchar();
                break;
            case '>':
                theta = OPTR.top();
                OPTR.pop();
                b=OPND.top();
                OPND.pop();
                a=OPND.top();
                OPND.pop();
                OPND.push(Operate(a, theta, b));
                break;
            }
    printf("%d\n",OPND.top());
    return 0;
}


猜你喜欢

转载自blog.csdn.net/DeathIsLikeTheWind/article/details/54951392