《编程思维与实践》1082.波兰表达式
题目
思路
法一(递归):
因为操作是对最近的两个数据进行,所以符合递推规律.
由于每组字符串之间都由空格分割,所以可以通过scanf读入,
同时注意到每一行结束必然会得到结果 所以不用担心会读入下一行的内容.
法二(栈模拟):
先将读入的字符串全部储存起来,再逆向遍历,遇到数据就入栈,遇到符号就取出栈中的两个元素运算完再入栈,
最终结果就是栈中的最后元素.
代码
法一(递归):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char s[11];
double cal()
{
scanf("%s",s);
if(strcmp(s,"+")==0)
{
return cal()+cal();
}
else if(strcmp(s,"-")==0)
{
return cal()-cal();
}
else if(strcmp(s,"*")==0)
{
return cal()*cal();
}
else if(strcmp(s,"/")==0)
{
return cal()/cal();
}
else
{
return atof(s);
}
}
int main()
{
int T;
scanf("%d\n",&T);
for(int t=0;t<T;t++)
{
printf("case #%d:\n",t);
printf("%.6lf\n",cal()); //每一行结束必然会得到结果 所以不用担心会读入下一行的内容
}
return 0;
}
法二(栈模拟):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
double stack[101];
int len=0;
double pop()
{
len--;
return stack[len];
}
void push(double f)
{
stack[len]=f;
len++;
}
int main()
{
int T;
scanf("%d",&T);
for(int t=0;t<T;t++)
{
stack[0]='\0'; //初始化栈
char str[101][11]; //存字符串
int i=0;
while(scanf("%s",str[i++]))
{
if(getchar()=='\n')
{
break;
}
}
for(int j=i-1;j>=0;j--) //逆向遍历
{
if(strcmp(str[j],"+")==0)
{
push(pop()+pop());
}
else if(strcmp(str[j],"-")==0)
{
push(pop()-pop());
}
else if(strcmp(str[j],"*")==0)
{
push(pop()*pop());
}
else if(strcmp(str[j],"/")==0)
{
push(pop()/pop());
}
else
{
push(atof(str[j]));
}
}
printf("case #%d:\n",t);
printf("%.6lf\n",pop());
}
return 0;
}