L2-033 简单计算器 (25 分)

思路:

用stl的stack模拟就好了,感觉比一些L1的都简单好多,而且没有坑点

代码:

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;

int n,a,ans;
char ch;
stack<int> s1;
stack<char> s2;
char op;

int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a;
        s1.push(a);
    }
    for(int i=1;i<n;i++){
        cin>>ch;
        s2.push(ch);
    }
    while(!s2.empty()){
        int n1=s1.top();
        s1.pop();
        int n2=s1.top();
        s1.pop();
        char op=s2.top();
        s2.pop();
        if(op=='/'){
            if(!n1){
                printf("ERROR: %d/0\n",n2);
                ans=-1;
                break;
            }
            else ans=n2/n1;
        }
        else if(op=='+') ans=n1+n2;
        else if(op=='-') ans=n2-n1;
        else if(op=='*') ans=n1*n2;
        s1.push(ans);
    }
    if(ans!=-1) cout<<ans<<endl;
    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值