Evaluate Postfix Expression

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 Infinitywhich 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

ElementType EvalPostfix(char *expr)
{
    double num[Max_Expr];
    int t = 0,n=0;
    for (int i = 0; expr[i] != '\0'; i++) {
        if (expr[i] == '-'&&expr[i + 1] >47) {
            i++;
            char temp[20] = { '\0' };
            int tem = 0; 
            while ((expr[i] >= '0'&&expr[i] <= '9')|| expr[i] == '.')
            {
                temp[tem++] = expr[i++];
            }
            num[t++] = -atof(temp);
            i--; n++;
            continue;
        }    
        else if ((expr[i] >= '0'&&expr[i] <= '9')|| expr[i]=='.') {
            char temp[20] = {'\0'};
            int tem = 0;
            while ((expr[i] >= '0'&&expr[i] <= '9') || expr[i] == '.')
            {
                temp[tem++] = expr[i++];
            }
            num[t++] = atof(temp);
            i--;
            n++;
            continue;
        }
        else if (expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/') {
            if (n < 2)  return Infinity;
            double result = 0;
            switch (expr[i]) {
            case '+':    result = num[t - 2] + num[t - 1];
                break;
            case '-':   result = num[t - 2] - num[t - 1];
                break;
            case '*':   result = num[t - 2] * num[t - 1];
                break;
            case '/':   if(num[t - 1]==0) return Infinity;
                result = num[t - 2] / num[t - 1];
                break;
            }
            t -= 2;
            num[t++] = result; n--;
        }
    }
    if(t!=1) return Infinity;
    else
        return num[0];
}
 

猜你喜欢

转载自blog.csdn.net/lannister_awalys_pay/article/details/83273523