题解 | 计算表达式 栈+ma设置优先级

计算表达式

https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string>
#include <stack>
#include <map>
using namespace std;

int main() {
    char str[1000] = { 0 };
    map<char, int> priority = { // 定义运算优先级
        {'\0', 0}, // 结束符优先级最低
        {'+', 1}, {'-', 1},
        {'*', 2}, {'/', 2},
    };

    while (scanf("%s", str) != EOF) {
        // !!! 空字符串,用于获取非单个数字(并不是只有一个字符)
        string numStr = "";
        stack<char> opStack; // 运算符栈
        stack<double>
        numStack; // 操作数栈(用double。!!!用int,除法会直接抹去小数)
        for (int i = 0; ; i++) { // !!! 可以后在循环体中写break条件
            if (str[i] >= '0' && str[i] <= '9') {
                numStr.push_back(str[i]);  // 拼接成字符串
            } else { // 碰到op操作符
                double num = stod(numStr);  //字符串转化为double类型变量
                numStr = ""; // 重新置空
                numStack.push(num); // 压入操作数栈中

                // !!!
                // 什么时候弹栈? 栈非空 && 新op的优先级(str[i]) 不高于(<=) 栈顶的优先级
                // 循环弹栈和计算 (用op栈顶操作符运算)
                while (!opStack.empty() &&
                        priority[str[i]] <= priority[opStack.top()]) {  // op栈非空
                    double rhs = numStack.top();
                    numStack.pop();
                    double lhs = numStack.top();
                    numStack.pop();
                    char curOp = opStack.top();
                    opStack.pop();

                    if (curOp == '+') {
                        numStack.push(lhs + rhs);
                    } else if (curOp == '-') {
                        numStack.push(lhs - rhs);
                    } else if (curOp == '*') {
                        numStack.push(lhs * rhs);
                    } else if (curOp == '/') {
                        numStack.push(lhs / rhs);
                    }
                }

                // 结束
                if (str[i] == '\0') {
                    printf("%d\n", (int)numStack.top()); // 强制转化为int型
                    break;  // 代码中间逻辑完成退出循环
                } else { // 栈为空 或者 新op的优先级高于栈顶
                    opStack.push(str[i]);   // 还有运算符
                }
            }

        }
    }
    return 0;
}

#考研##复试练习#
2025考研复试 文章被收录于专栏

复试ing,努力中。。。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务