题目链接:https://www.luogu.org/problemnew/show/P1449
题目思路:由题目意思可以想到用栈的思想来做,具体操作是遇到数字压入栈,遇到运算符就弹出两个被操作的数并将运算的结果压入栈。最后在栈底元素就是表达式的值。
代码如下:(采用数组模拟栈的方法)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
int main(){
char c[1005];
gets(c);//读入
int len=strlen(c);
int stack[1005];
int top=0;
int i=0,x=0;
while(i<=len-2){//直接避免'@'
if(c[i]>='0'&&c[i]<='9'){
x*=10;
x+=c[i]-'0';字符转化为数字
}
else if(c[i]=='.'){
stack[++top]=x;//数字入栈
x=0;
}
else if(c[i]=='+'){
stack[--top]+=stack[top+1];//对被操作数进行操作
}
else if(c[i]=='-'){
stack[--top]-=stack[top+1];
}
else if(c[i]=='*'){
stack[--top]*=stack[top+1];
}
else if(c[i]=='/'){
stack[--top]/=stack[top+1];
}
i++;//下一个字符
}
printf("%d\n",stack[top]);输出
return 0;
}
总结:这道题同来练习基础的栈还是可以的。