4-5 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 valueInfinity
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef double ElementType;
#define Infinity 1e8
#define Max_Expr 30 /* max size of expression */
double calculate(double number1,double number2,char ch)
{
if(ch=='+')
return number1+number2;
else if(ch=='-')
return number2-number1;
else if(ch=='*')
return number1*number2;
else{
if(fabs(number1)<=0.0000000001)
return (double)Infinity;
return number2/number1;
}
}
ElementType EvalPostfix( char *expr )
{
double result=0;//两个操作数计算的结果
double number[100];//栈,把操作数放入栈中
int top=-1;
int start=-1;//操作数开始的下标
//输入直接为单独一个操作数
int flag=0;
for(int j=0;expr[j];j++){
if(j==0){
if(expr[j]!='-'&&!isdigit(expr[j]))
flag=1;
}
else if(expr[j]!='.'&&!isdigit(expr[j]))
flag=1;
}
if(!flag)
return atof(expr);
//常规处理
for(int i=0;expr[i];i++){
if((expr[i]=='+'||expr[i]=='-'||expr[i]=='*'||expr[i]=='/')&&(expr[i+1]==' '||expr[i+1]=='\0')){
if(top<1){//出现运算符,但操作数个数不够2了
return (double)Infinity;
}
double number1=number[top--];
double number2=number[top--];
result=calculate(number1,number2,expr[i]);
if(result>=Infinity)//中间结果大于Infinity就结束
return (double)Infinity;
number[++top]=result;//结果入栈
}
else if(expr[i]!=' '&&start==-1)//新出现一个操作数
start=i;
else if(expr[i]==' '){
expr[i]='\0';//空格均赋'\0',以便利用atof()化字符串为double
if(isdigit(expr[i-1])){//当前操作数到结束位置
double temp=atof(expr+start);
number[++top]=temp;
start=-1;//存完当前操作数,重置start,以读取下一个操作数
}
}
else if(strchr("0123456789.+-*/",expr[i])==NULL)//判断非法字符
return (double)Infinity;
}
//最后出现的不是运算符,而为操作数 如:5 6 * 14
if(start!=-1)
return (double)Infinity;
//最后栈内剩余多个操作数
if(top!=0)
return (double)Infinity;
//栈头即为结果
return number[0];
}
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 */