题解 | #简单计算器#

简单计算器

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

#include<cstdio>
#include<string>
#include<map>
#include<stack>

using namespace std;
int main() {
    char arr[300];
    map<char, int> priority = {//记录输入的优先级
        {'$', 0},
        {'+', 1},
        {'-', 1},
        {'*', 2},
        {'/', 2},
    };
    while (fgets(arr, sizeof(arr), stdin) != NULL) {
        string ear = arr;
        ear.pop_back();
        if (ear == "0") {
            break;
        }
        ear.push_back('$');//给表达式末尾加上$
        stack<double> numStack;
        stack<char> opearStack;
        string nums;
        for (int i = 0; i < ear.size(); ++i) {//开始遍历表达式
            if (ear[i] >= '0' && ear[i] <= '9') {
                nums.push_back(ear[i]);//把数字压入数字栈
            } else if (ear[i] == ' ') {
                if (nums != " ") {
                    numStack.push(stod(nums));
                    nums = " ";
                }
            } else {
                if (ear[i] == '$') {
                    if (nums != " ") {
                        numStack.push(stod(nums));
                        nums = " ";
                    }
                }
                while (!opearStack.empty() && priority[ear[i]] <= priority[opearStack.top()]) {
                    char oper = opearStack.top();//操作符
                    opearStack.pop();
                    double rhs = numStack.top();//运算数1
                    numStack.pop();
                    double lhs = numStack.top();//运算数2
                    numStack.pop();

                    switch (oper) {
                        case '+' :
                            numStack.push(lhs + rhs);
                            break;
                        case '-' :
                            numStack.push(lhs - rhs);
                            break;
                        case '*' :
                            numStack.push(lhs * rhs);
                            break;
                        case '/' :
                            numStack.push(lhs / rhs);
                            break;
                    }

                }
                opearStack.push(ear[i]);

            }

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

全部评论

相关推荐

AFBUFYGRFHJLP:直接去美帝试试看全奖phd吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务