4-5-Evaluate Postfix Expression

来源:互联网 发布:mac mysql安装 编辑:程序博客网 时间:2024/05/07 05:39
4-5 Evaluate Postfix Expression

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
为简化代码, 该函数使用了atof()--字符串转数字 isdigit()--判断数字 strchr()--比较字符, 具体信息请自行google.
ElementType EvalPostfix( char *expr ){ElementType Stk[Max_Expr], op1, op2;char *temp;int i=0, Top=-1, flag=0;for(i=0;expr[i];i++){     /* 判断输入的是否为单个数字 */        if(i==0){if(expr[0]=='-'&&expr[1]=='\0')   /* 区分输入为一个负数或一个负号 */return Infinity;            if(expr[0]!='-'&&!isdigit(expr[0]))                flag=1;        }        else if(expr[i]!='.'&&!isdigit(expr[i]))flag=1;    }    if(!flag)        return atof(expr);i=0;while(expr[i]!='\0'){if(expr[i]==' '){expr[i++] = '\0';   /* 把空格换成\0 变成另一个字符串temp 方便使用atof等 */temp = expr;expr += i;       /* expr指向剩余字符串 */i = 0;if(!strchr("0123456789.+-*/",temp[0])) /* 非法字符 */return Infinity;if(strchr("+-*/",temp[0])&&temp[1]=='\0'){ /* 操作符 */if(Top-2 < -1)return Infinity;op1 = Stk[Top--];op2 = Stk[Top--];if(temp[0] == '+')Stk[++Top] = op1 + op2;else if(temp[0] == '-')Stk[++Top] = op2 - op1;else if(temp[0] == '*')Stk[++Top] = op1 * op2;else if(temp[0] == '/'){if(op1==0)return Infinity;Stk[++Top] = op2 / op1;}}else                                     /* 数字 */Stk[++Top] = atof(temp);}elsei++;}temp = expr;      /* 处理最后一个字符 */if(Top-2 != -1)   /* 合法的表达式最后一个字符应为操作符,需要两个操作数 */return Infinity;op1 = Stk[Top--];op2 = Stk[Top--];if(temp[0] == '+')Stk[++Top] = op1 + op2;else if(temp[0] == '-')Stk[++Top] = op2 - op1;else if(temp[0] == '*')Stk[++Top] = op1 * op2;else if(temp[0] == '/'){if(op1==0)return Infinity;Stk[++Top] = op2 / op1;}else              /* 输入单个非法字符或最后一个字符是非法的 */return Infinity;return Stk[0];}
1 0
原创粉丝点击