3-4 Evaluate Postfix Expression (15 分)
Write a program to evaluate a postfix expression. You only have to handle four kinds of operators: +, -, x, and /.
Format of functions:
ElementType EvalPostfix( char *expr );
where expr points to a string that stores the postfix expression. It is guaranteed that there is exactly one space between any two operators or operands. The function EvalPostfix is supposed to return the value of the expression. If it is not a legal postfix expression, EvalPostfix must return a special value Infinity which is defined by the judge program.
Sample program of judge:
#include <stdio.h>
#include <stdlib.h>
typedef double ElementType;
#define Infinity 1e8
#define Max_Expr 30 /* max size of expression */
ElementType EvalPostfix( char *expr );
int main()
{
ElementType v;
char expr[Max_Expr];
gets(expr);
v = EvalPostfix( expr );
if ( v < Infinity )
printf("%f\n", v);
else
printf("ERROR\n");
return 0;
}
/* Your function will be put here */
Sample Input 1:
11 -2 5.5 * + 23 7 / -
结尾无空行
Sample Output 1:
-3.285714
结尾无空行
Sample Input 2:
11 -2 5.5 * + 23 0 / -
Sample Output 2:
ERROR
Sample Input 3:
11 -2 5.5 * + 23 7 / - *
Sample Output 3:
ERROR
分析:
题目的意思是将给出的后缀表达式进行计算,返回结果
后缀表达式:遇到数字进栈,遇到运算符,出栈两个元素,进行运算,再进栈,需要注意的是,出栈的元素为A(先出),B(后出),运算为:B(±*/)A
是有先后顺序的
AC代码如下:
ElementType EvalPostfix( char *expr ){
int i,j,k,l,top=-1;
l=strlen(expr);
double sum[5000] = {0};
for(i=0;i<l;i++){
j=i;
while(expr[i]!=' '&&expr[i]!='\0')
i++;
/*分段处理*/
double temp = 0;
int flag1 = 0;//标记是否为负数
int flag2 = 0;//标记是否为小数
int flag3 = 0;//标记是否进入运算
for(k=j;k<i;k++){
if(expr[k]=='+'){
if(top<1)
return Infinity;
temp = sum[top--] + sum[top--];
sum[++top]=temp;
flag3 = 1;
break;
}
else if(expr[k]=='*'){
if(top<1)
return Infinity;
temp = sum[top--] * sum[top--];
sum[++top]=temp;
flag3 = 1;
break;
}
else if(expr[k]=='/'){
if(top<1||sum[top]==0)
return Infinity;
temp = sum[top-1]/sum[top];
sum[--top]=temp;
flag3 = 1;
break;
}
else if(expr[k]=='.'){
flag2=1;
continue;
}
else if(expr[k]=='-' && expr[k+1]!='\0' && expr[k+1]!=' '){
flag1=1;
continue;
}
else if(expr[k]=='-'){
if(top<1)
return Infinity;
temp = sum[top-1]-sum[top];
sum[--top]=temp;
flag3 = 1;
break;
}
/*算数*/
else{
if(flag2!=0){
temp=temp+(expr[k]-'0')*pow(0.1,flag2);
flag2++;
}
else{temp=temp*10 + (expr[k]-'0');}
}
}
if(flag3==1)
continue;
if(flag1==1)
sum[++top]=-temp;
else
sum[++top]=temp;
}
if (top - 1 == -1)
return sum[0];
return Infinity;
}