#include #include #include using namespace std;

int main() { int N; cin >> N;

stack<int> nums;
stack<char> operators;

for (int i = 0; i < N; i++) {
    int num;
    cin >> num;
    nums.push(num);
}

for (int i = 0; i < N - 1; i++) {
    char op;
    cin >> op;
    operators.push(op);
}

while (!operators.empty()) {
    int n1 = nums.top();
    nums.pop();
    
    int n2 = nums.top();
    nums.pop();
    
    char op = operators.top();
    operators.pop();
    
    int result;
    if (op == '+') {
        result = n2 + n1;
    } else if (op == '-') {
        result = n2 - n1;
    } else if (op == '*') {
        result = n2 * n1;
    } else if (op == '/') {
        if (n1 == 0) {
            cout << "ERROR: " << n2 << "/0" << endl;
            return 0;
        } else {
            result = n2 / n1;
        }
    }
    
    nums.push(result);
}

cout << nums.top() << endl;

return 0;
编写一个C++代码本题要求你为初学数据结构的小伙伴设计一款简单的利用堆栈执行的计算器。如上图所示计算器由两个堆栈组成一个堆栈 S 1 存放数字另一个堆栈 S 2 存放运算符。计算器的最下方有一个等号键每次按下这个键计算器就执行以下操作:从 S 1 中弹出两个数字顺序为 n 1 和 n 2 ;从 S 2 中弹出一个运算符 op;执行计算 n 2 op n 1 ;将得到的结

原文地址: http://www.cveoy.top/t/topic/h72W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录