L2-033 简单计算器

#include <bits/stdc++.h>

using namespace std;

int cal(int a, int b, char c) {
    int t;
    if (c == '/' && b == 0) t = -1;
    else if (c == '+') t = a + b;
    else if (c == '-') t = a - b;
    else if (c == '*') t = a * b;
    else if (c == '/') t = a / b;
    return t;
}

int main() {
    stack<int> num;
    stack<char> op;
    int n;
    cin >> n;
    vector<int> v(n + 1);
    for (int i = 1; i <= n; i++) {
        int x;
        cin >> x;
        num.push(x);
    }
    for (int i = 0; i < n - 1; i++) {
        char o;
        cin >> o;
        op.push(o);
    }
    if (n == 1) cout << num.top() << "\n";
    else {
        int n1, n2;
        while (num.size()) {
            if (num.size()) {
                n1 = num.top();
                num.pop();
            } 
            if (num.size()) {
                n2 = num.top();
                num.pop();
            }
            if (num.empty()) {
                break;
            } 
            int t = cal(n2, n1, op.top());
            if (t == -1) {
                cout << "ERROR: " << n2 << "/" << 0 << "\n";
                return 0;
            }
            op.pop();
            num.push(t);
        }
        int t = cal(n2, n1, op.top());
        if (t == -1) {
            cout << "ERROR: " << n2 << "/" << 0 << "\n";
        } else {
            cout << t << "\n";
        }
    }

    return 0;
}
posted @ 2022-04-16 10:25  Xxaj5  阅读(21)  评论(0编辑  收藏  举报