L2-033 简单计算器

这题可以与acwing的表达式求值联系起来3302
本题传送门
还可以结合L2-053传送门
不过acwing和053的题目难多了,本题压根不需要单调栈的知识。

没什么好讲的,只是引出后面的题目

ac✅️代码

#include<iostream>
#include<stack>
using namespace std;
stack<int> val;
stack<char> op;

int main()
{
    int n;
    cin>>n;
    for(int i = 0 ; i < n ; i++)
        {
            int x;cin>>x;
            val.push(x);
            
        }
    for(int j = 0 ; j < n-1 ; j ++)
        {
            char x;cin>>x;
            op.push(x);
        }
    while(val.size() != 1)
        {
            int n1 = val.top();
            val.pop();
            int n2 = val.top();
            val.pop();
            char pr = op.top();
            op.pop();
            if(pr == '+') val.push(n1+n2);
            if(pr == '-') val.push(n2-n1);
            if(pr == '*') val.push(n2*n1);
            if(pr == '/') 
            {
                if(n1 == 0)
                {
                    printf("ERROR: %d/%d\n",n2,n1);
                    return 0;
                }
                else val.push(n2/n1);
            }
        }
    cout<<val.top()<<endl;
    return 0;
} 
posted @ 2026-03-16 21:32  shuiwangrenjia  阅读(18)  评论(0)    收藏  举报