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