算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。
输入格式说明:
输入在一行内给出不超过30个字符的前缀表达式,只包含+、-、*、\以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式说明:
输出前缀表达式的运算结果,精确到小数点后1位,或错误信息“ERROR”。
样例输入与输出:
序号 | 输入 | 输出 |
1 | + + 2 * 3 - 7 4 / 8 4 | 13.0 |
2 | / -25 + * - 2 3 4 / 8 4 | 12.5 |
3 | / 5 + * - 2 3 4 / 8 2 | ERROR |
4 | +10.23 | 10.2 |
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<iostream>
#include<algorithm>
using namespace std;
stack<double>p;
int main()
{
int i,l,t,k;
char a[10010];
double s,x,y;
while(gets(a))
{
t=1;
s=0;
k=0;
l=strlen(a);
for(i=l-1;i>=0;i--)
{
if(a[i]>='0' && a[i]<='9')
{
s+=(a[i]-'0')*t*1.0;//考虑数会大于9
t*=10;
}
else if(a[i]=='.')
{
s=s*(1.0/t);
t=1;//小数的情况
}
else if((a[i]=='+' || a[i]=='-') && s!=0)//当有负号要特殊考虑
{
if(a[i]=='-')
s=-s;
p.push(s);
i--;//?
}
else if(a[i]==' ')
{
p.push(s);
s=0;
t=1;
}
else
{
x=p.top();
p.pop();
y=p.top();
p.pop();
if(a[i]=='+')
p.push(x+y);
if(a[i]=='-')
p.push(x-y);
if(a[i]=='*')
p.push(x*y);
if(a[i]=='/')
{
if(y==0)
{
printf("ERROR\n");
k=1;
break;
}
p.push(x/y);
}
i--;//?
}
}
if(k==0)
printf("%.1lf\n",p.top());
}
return 0;
}