题解 | #简单计算器#

简单计算器

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

//
// Created by Virtus on 2024/2/21.
//
#include <iostream>
#include <cctype>
#include <string>
#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(double x, double y, char op) {
    if (op == '+') {
        return x + y;
    } else if (op == '-') {
        return x - y;
    } else if (op == '*') {
        return x * y;
    } else {
        return x / y;
    }
}

int main() {
    string str;
    while (getline(cin, str)) {
        if (str == "0") {
            break;
        }
        int index = 0;            // 字符串索引
        stack<char> op;           // 运算符栈
        stack<double> data;       // 运算数栈
        str += '$';               // 字符串尾部添加$
        op.push('#');          // 运算符栈底部添加#
        while (index < str.size()) {
            if (str[index] == ' ') {
                index++;
            } else if (isdigit(str[index])) {
                data.push(getNumber(str, index));
            } else {
                if (priority(op.top()) < priority(str[index])) {
                    op.push(str[index]);
                    index++;
                } else {
                    double y = data.top();
                    data.pop();
                    double x = data.top();
                    data.pop();
                    data.push(calculate(x, y, op.top()));
                    op.pop();
                }
            }
        }
        printf("%.2f\n", data.top());
    }
    return 0;
}

全部评论

相关推荐

2025-12-17 17:15
华东师范大学 运营
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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