题解 | #简单计算器#

简单计算器

https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130

#include <iostream>
#include <stack>

using namespace std;

bool isOp(char x){
    if (x=='+' || x=='-' || x=='*' || x=='/' || x=='#'){
        return true;
    }
    return false;
}

int priority(char op){
    if (op=='+' || op=='-'){
        return 1;
    } else if (op=='*' || op=='/'){
        return 2;
    } 
    return 0;
}

double yunsuan(double x, double y, char op){
    switch (op) {
        case '+': return x+y;
        case '-': return x-y;
        case '*': return x*y;
        case '/': return x/y;
        default: return 0;
    }
}

int main() {

    string str;
    while (getline(cin, str)){
        if (str == "0") break;
        str.push_back('#');
        stack<double> num;
        stack<char> op;
        string number;

        for (int i = 0; i < str.size(); ++i) {
            if ('0'<=str[i] && str[i]<='9'){
                number.push_back(str[i]);
            } else if (str[i]==' ' && !number.empty()){
                num.push(stod(number));
                number = "";
            } else if (isOp(str[i])){
                if (str[i]=='#'){
                    num.push(stod(number));
                }

                while (!op.empty() && priority(op.top()) >= priority(str[i])){
                    double y = num.top();
                    num.pop();
                    double x = num.top();
                    num.pop();
                    char oper = op.top();
                    op.pop();
                    double result = yunsuan(x, y, oper);
                    num.push(result);
                }
                op.push(str[i]);
            }
        }

        printf("%.2lf\n", num.top());

    }

    return 0;
}

全部评论

相关推荐

听说改名字就能收到offer哈:Radis写错了兄弟
点赞 评论 收藏
分享
11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务