6-1 Evaluate Postfix Expression (25 分)
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
Special thanks to Sirou Zhu (朱思柔) for providing a valuable test case.
ElementType EvalPostfix( char *expr ){
double a[100]; //存储数据,模拟栈
char b[100]; //从表达式取字符
int i=0,k=0; //记步
while (expr[i]!='\0') {
int j=0;
while (expr[i]==' ') { //去掉表达式前面的空格和转换成数字后的空格
i++;
}
while((expr[i]=='.')||(expr[i]<='9'&&expr[i]>='0')||(expr[i]=='-'&&(expr[i+1]!=' '&&expr[i+1]!='\0'))){
b[j]=expr[i];
j++;
i++;
}//读取字符
if(expr[i]==' '||(k==0&&expr[i+1]=='\0')) {
a[k]=atof(b);
memset(b,0,sizeof(b));
i++;
k++;
}//将字符转化为double类数据
else if(expr[i]!=' '&&(expr[i]>'9'||expr[i]<'0')&&(expr[i+1]==' '||expr[i+1]=='\0')){
switch (expr[i]) {
case '+':
a[k-2]=a[k-1]+a[k-2];
break;
case '-':
a[k-2]=a[k-2]-a[k-1];
break;
case '*':
a[k-2]=a[k-1]*a[k-2];
break;
case '/':
if (a[k-1]==0) {
return Infinity;
}
a[k-2]=a[k-2]/a[k-1];
break;
default:
break;
}
i++;
k--;
}//检查到运算符,运算
}
if (k==0) {
return Infinity;
}
return a[k-1];
}