题解 | 简单计算器

简单计算器

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

#include <stdio.h>
#include <stack>
#include <string>
#include <map>
#include <string.h>

using namespace std;
int main() {
    char str[200];
    map<char, int> priority = {
        {'\0', 0},
        {'+', 1}, {'-', 1},
        {'*', 2}, {'/', 2},
    };
    while (fgets(str, 200, stdin)) {
        // 移除末尾的换行符(如果有)
        str[strcspn(str, "\n")] = '\0';
        string s = str;
        if (s[0] == '0') { //如果输入的是数字0表示循环输入结束
            break;
        }
        stack<char> opStack;//运算符栈
        stack<double> numStack;//操作数栈
        string numStr = "";
        for (int i = 0 ; ; i++) {
            if (s[i] >= '0' && s[i] <= '9') { //字符数字进行拼接
                numStr += s[i];
            } else if (s[i] == ' ') {
                continue;
            } else { //遍历到运算符,数字字符串拼接结束
                double num = stod(numStr);//转成double数字并压入操作数栈
                numStack.push(num);
                numStr = "";
                //当栈中运算符不为空且栈顶运算符优先级大于等于当前运算符时(即将要进入的)遍历到的
                //此时运算符栈弹出一个栈顶运算符,操作数栈弹出2个数进行运算,中间结果压回操作数栈
                while (!opStack.empty() && priority[opStack.top()] >= priority[s[i]]) {
                    char cur_op =
                        opStack.top();//将对应栈顶运算符先保存在一个变量中
                    opStack.pop(); //从运算符栈中弹出
                    //操作数栈,弹出2个数并保存起来,先出的是右操作数
                    double rhs = numStack.top();//右操作数
                    numStack.pop(); //弹栈
                    double lhs = numStack.top();//左操作数
                    numStack.pop(); //弹栈
                    //根据当前栈顶运算符进行对应的运算,中间结果压回操作数栈
                    if ( cur_op == '+' ) {
                        double res = lhs + rhs;
                        numStack.push(res);
                    } else if ( cur_op == '-') {
                        double res = lhs - rhs;
                        numStack.push(res);
                    } else if ( cur_op == '/') {
                        double res = lhs / rhs;
                        numStack.push(res);
                    } else {
                        double res = lhs * rhs;
                        numStack.push(res);
                    }
                }
                //栈顶运算符的优先级小于当前运算符s[i]优先级或者运算符栈为空(与上一个while循环条件相反)
                if (s[i] ==
                        '\0') { //当计算表达式字符串遍历到字符\0说明计算已经结束操作数栈中只剩一个最终运算结果
                    printf("%.2f\n", numStack.top()); //输出最终运算结果
                    break; //退出死循环
                } else { //当还没有遍历到结束符
                    // 且栈顶运算符的优先级小于当前运算符s[i]优先级或者运算符栈为空将当前运算符压入运算符栈中!
                    opStack.push(s[i]);
                }
            }
        }
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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