题解 | #简单计算器#

简单计算器

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

#include <iostream>
#include<stack>
//参考答案解法,磕磕绊绊,还不熟练
using namespace std;
int priority(char c) {
    if (c == '#') { //运算符栈
        return 0;
    } else if (c == '$') {
        return 1;
    } else if (c == '+' || c == '-') {
        return 2;
    } else {
        return 3;
    }
}
double getNumber(string str, int& index) { //获得索引
    double number = 0;
    while (isdigit(str[index])) { //判断是否是数字
        number = number * 10 + str[index] - '0';
        index++;
    }
    return number;
}
double Calculate(char operSign, double operNum1, double operNum2) {
    double resultNum = 0;
    if (operSign == '+') {
        resultNum = operNum1 + operNum2;
    } else if (operSign == '-') {
        resultNum = operNum1 - operNum2;
    } else if (operSign == '*') {
        resultNum = operNum1 * operNum2;
    } else if (operSign == '/') {
        resultNum = operNum1 / operNum2;
    }
    return resultNum;
}
int main() {
    string str;
    while (getline(cin, str)) {
        if (str == "0") break; //双引号,0就退出
        stack<double> data;
        stack<char> oper;
        int index = 0;
        str += '$';
        oper.push('#');
        while (index < str.size()) {
            if (isdigit(str[index])) {
                data.push(getNumber(str, index));

            } else if (str[index] == ' ') {
                index++;
            } else {
                if (priority(oper.top()) < priority(str[index])) {
                    oper.push(str[index]);
                    index++;
                } else {
                    double x = data.top();
                    data.pop();
                    double y = data.top();
                    data.pop();
                    data.push(Calculate(oper.top(), y, x));
                    oper.pop();
                }
            }

        }
        printf("%.2f\n", data.top());

    }
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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