题解 | 计算表达式

计算表达式

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

#include <iostream>
#include<stack>

using namespace std;

bool opPriority(char op1, char op2) {
    if ((op1 == '/' || op1 == '*') && (op2 == '-' || op2 == '+'))return true;
    return false;
}

double caculate(double a, double b, char op) {
    switch (op) {
        case '-':
            return a - b;
        case '+':
            return a + b;
        case '/':
            return a / b;
        case '*':
            return a * b;
    }
    return 0;
}

int main() {
    string s;
    while (cin >> s) { // 注意 while 处理多个 case
        stack<double>numstack;
        stack<char>opstack;
        for (int i = 0; i < s.length();) {
            double num = 0;
            int flag=1;
            if(i==0&&s[i]=='-'){
                flag=-1;
                i++;
            }
            if(isdigit(s[i])){
                while (isdigit(s[i])) {
                    num = num * 10 + s[i] - '0';
                    i++;
                }
                if(flag==-1)num=-num;
                numstack.push(num);
            }else if (opstack.empty() || opPriority(s[i], opstack.top())){
                opstack.push(s[i]);
                i++;
            }else {
                while (!opstack.empty() && !opPriority(s[i], opstack.top())) {
                    double a = numstack.top();numstack.pop();
                    double b = numstack.top();numstack.pop();
                    numstack.push(caculate(b, a, opstack.top()));
                    opstack.pop();
                }
                opstack.push(s[i]);
                i++;
            }
        }
        while(!opstack.empty()){
            double a=numstack.top();numstack.pop();
            double b=numstack.top();numstack.pop();
            numstack.push(caculate(b, a, opstack.top()));opstack.pop();
        }
        cout<<numstack.top()<<endl;

    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

2025-12-19 19:02
西安交通大学 Java
程序员牛肉:双九,而且还是西交这种比较好的985九没必要再投日常了。你投中小厂,人家会觉得你学历这么顶还面试肯定是海投的,过了你也不去。所以不约你了。 直接准备暑期实习就好,现在你可以面试。但是目的不再是去日常实习了,而是熟悉面试节奏。 后续把精力放到八股,算法和AI知识上。抽空把自己这两个项目换了,怎么选项目可以看看我主页写的文章。 你学历不错的,不要焦虑
那些拿到大厂offer的...
点赞 评论 收藏
分享
01-09 17:12
四川大学 Java
叁六玖:上次建行给我开25万,让我扣2办理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务