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#include typedef double ElementType; #define Infinity 1e8 #define Max_Expr 30 ElementType evalPostfix( char *expr ); int main() { ElementType v; char expr[Max_Expr]; gets(expr); v = evalPostfix( expr ); if ( v < Infinity ) printf("%fn", v); else printf("ERRORn"); return 0; }
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欢迎分享,转载请注明来源:内存溢出
评论列表(0条)