• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

waterrzhang

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

四则运算

#include <iostream>
#include <string>
#include <stack>

using namespace std;

bool cmpPriority(char top, char cur)  //top的优先级高于cur时,返回ture,此处不将当前值与‘(’对比
{
    if ((top == '+' || top == '-') && (cur == '+' || cur == '-'))
        return true;
    if ((top == '*' || top == '/') && (cur == '+' || cur == '-' || cur == '*' || cur == '/'))
        return true;
    return false;
}

void preProcess(string &str)
{
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] == '{' || str[i] == '[')
            str[i] = '(';
         if (str[i] == '}' || str[i] == ']')
            str[i] = ')';
         if (str[i] == '-')
         {
            if (i == 0 || str[i - 1] == '(')
                str.insert(i, 1, '0');
         }
    }
}

void doCal(stack<int>& numStack, stack<char>& operStack)
{
    int b = numStack.top();         //注意运算顺序,a+b压入栈后,b在上
    numStack.pop();
    int a = numStack.top();
    numStack.pop();
    char op = operStack.top();
    operStack.pop();

    switch (op)
    {
        case '+':   a += b; break;
        case '-':   a -= b; break;
        case '*':   a *= b; break;
        case '/':   a /= b; break;
    }

    numStack.push(a);
}

int main()
{
    string s;
    while (getline(cin, s))
    {
        preProcess(s);
        stack<int> numStack;
        stack<char> operSatck;

        operSatck.push('(');   //确保栈顶有值
        s.push_back(')');

        for (int i = 0; i < s.size(); i++)
        {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{')
                operSatck.push('(');
            else if (s[i] == ')' || s[i] == ']' || s[i] == '}')
            {
                while (operSatck.top() != '(')
                        doCal(numStack, operSatck);
                operSatck.pop();
            }
            else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')  //
            {
                while (cmpPriority(operSatck.top(), s[i]))
                    doCal(numStack, operSatck);
                operSatck.push(s[i]);
            }
            else if (isdigit(s[i]))
            {
                int j = i;
                while (i < s.size() && isdigit(s[i]))
                {
                    i++;
                }
                string temp = s.substr(j, i - j);
                numStack.push(stoi(temp));
                i--;
            }

        }
        cout << numStack.top() << endl;
    }
    return 0;
}

 

posted on 2020-09-01 11:26  waterrzhang  阅读(126)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3