时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如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 <iostream>
#include <malloc.h>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
char s[200];
int len,i,k=0;
double a[200];
gets(s);
len=strlen(s);
for(i=len-1;i>=0;i--)
{
//cout<<i<<"="<<s[i]<<endl;
if(s[i]==' ')
continue;
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
{
if(s[i+1]!=' ')
continue;
double first = a[--k];
double second = a[--k];
//cout<<first<<" "<<s[i]<<" "<<second<<endl;
switch(s[i])
{
case '+':
a[k]=first+second;
break;
case '-':
a[k]=first-second;
break;
case '*':
a[k]=first*second;
break;
case '/':
if(second==0)
{
cout<<"ERROR\n";
return 0;
}
a[k]=first/second;
break;
}
//cout<<"k="<<k<<" a[k]="<<a[k]<<endl;
k++;
continue;
}
int tmp=i;
while(s[i]!=' '&&i>=0)
{
i--;
}
int flag=1;
if(s[++i]=='-')
{
flag = -1;
i++;
}else if(s[i]=='+')
{
i++;
}
double num=0;
int tmp0=i;
while(tmp0<=tmp)
{
//cout<<s[tmp0]<<" ";
if(s[tmp0]=='.')
{
tmp0++;
int point=1;
while(tmp0<=tmp)
{
//cout<<"tmp0:"<<s[tmp0]<<endl;
double re=s[tmp0]-'0';
int pointtmp = point;
while(pointtmp--)
re*=0.1;
point++;
num+=re;
//cout<<num<<endl;
tmp0++;
}
break;
}
num=num*10+(s[tmp0]-'0');
tmp0++;
}
//if(flag<0)
//cout<<num<<" "<<a[k]<<endl;
a[k++]=num*flag;
//cout<<"i="<<i<<endl;
//cout<<"k="<<k-1<<" a[k]="<<a[k-1]<<endl;
}
printf("%.1f\n",a[0]);
return 0;
}