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



    #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] = { '+', '-', '*', '/', '(', ')', '
    ' };
    
    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('
    ');
        c = getchar();
        while (c != '
    ' || OPTR.top() != '
    ')
            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
    ",OPND.top());
        return 0;
    }
    


  • 相关阅读:
    phpQuery—基于jQuery的PHP实现
    php 知乎爬虫
    windows下安装php5.5的redis扩展
    Redis 安装
    使用AngularJS创建应用的5个框架
    Redis能干啥?细看11种Web应用场景
    前端开发必须知道的JS之闭包及应用
    javascript深入理解js闭包
    day16<集合框架+>
    day15<集合框架>
  • 原文地址:https://www.cnblogs.com/chinashenkai/p/9451394.html
Copyright © 2020-2023  润新知