洛谷p1449后缀表达式

看了很多题解,也受了很多前辈的鼓励,让我来写一篇,所用方法尽可能简单和详细,作为一名小白,我十分理解小白,一下代码都会有十分详细的注释和一些已经被注释掉的,可以用来观察程序的进程,以及程序到底是在哪一步偏离了我们的想法,话不多说,上代码。

/*
1.对题面进行解释:遇见数字,则将数字压入栈,碰见符号,则将最上面的两个数字取出,进行运算,再将结果压入栈
重复操作,直至栈中剩下一个数字,进行输出
2.思路:首先将输入读入数组,直至碰见@终止符
将数组分别压入栈,然后遵循1的操作即可 
数字的ascii码  范围    47<x<58 
*/
#include <bits/stdc++.h>
using namespace std;
int f,s;       //两个变量用来存放栈的两个临时元素
char q;        //用来存放碰见的临时字符
char  a[1005],b[1005]; 
int a1,a2,a3;
int ans;
int main()
{
    int c;
    stack<int> shu;
    scanf("%s",a);
    int n=strlen(a);
//    for(int i=0; i<n; i++) printf("%c",a[i]);  //检测读入是否有问题 
    for(int i=0; i<n; i++){
        if(a[i]=='@') break;
        if(a[i]>='0'&&a[i]<='9'){
            int q=a[i]-'0';
            ans=ans*10+q;
        }
        else if(a[i]=='+'){
            a1=shu.top();
            shu.pop();
            a2=shu.top();
            shu.pop();
                a3=a1+a2;
                shu.push(a3);
/*                printf("执行了加法  且运算后的数字为%d\n",a3);    检测运算进程 
                for(int j=0; j<shu.size(); j++) printf("%d ",shu.top());
                printf("\n");*/
            }else if(a[i]=='-'){
                a1=shu.top();
            shu.pop();
            a2=shu.top();
            shu.pop();
                a3=a2-a1;
                shu.push(a3);
/*                printf("执行了减法  且运算后的数字为%d\n",a3);
                for(int j=0; j<shu.size(); j++) printf("%d ",shu.top());
                printf("\n");*/
            }else if(a[i]=='*'){
                a1=shu.top();
            shu.pop();
            a2=shu.top();
            shu.pop();
                a3=a1*a2;
                shu.push(a3);
/*                printf("执行了乘法  且运算后的数字为%d\n",a3);
                for(int j=0; j<shu.size(); j++) printf("%d ",shu.top());
                printf("\n");*/
            }else if(a[i]=='/'){
                a1=shu.top();
            shu.pop();
            a2=shu.top();
            shu.pop();
                a3=a2/a1;
                shu.push(a3);
/*                printf("执行了除法  且运算后的数字为%d\n",a3);
                for(int j=0; j<shu.size(); j++) printf("%d ",shu.top());
                printf("\n");*/
            }else{
                shu.push(ans);
                ans=0;
            }
        }
//    printf("%d\n",c);  //检测数字读入个数 
    printf("%d",shu.top());
    return 0;
 } 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值