2011-12-25 15:48:22
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1237
题意:中文。
mark:用递归替代栈。1WA。开始没考虑到1 - 2 + 2的情况。把2+2先算了。。。
代码:
# include <stdio.h># include <string.h>char str[1010] ;double num[1010] ;char op[1010] ;int cnt ;void getWord (){ double buff = 0 ; int i, flag = 0 ; for (i = 0 ; str[i] ; i++) { if (flag == 0) { if (str[i] == ' ') { flag = 1 ; num[cnt] = buff ; } else buff = buff * 10 + (str[i] -'0') ; } else { op[cnt++] = str[i] ; buff = 0 ; i++ ; flag = 0 ; } } num[cnt] = buff ;}double fun(double a, double b, char op){ double ans ; switch (op) { case '+':ans = a+b ; break ; case '-':ans = a-b ; break ; case '*':ans = a*b ; break ; case '/':ans = a/b ; break ; } return ans ;}double calc(int n){ if (n == cnt-1) return fun(num[n], num[n+1], op[n]) ; if (op[n] == '+') return fun(num[n], calc(n+1), op[n]) ; if (op[n] == '-') { num[n+1] = -num[n+1] ; op[n] = '+' ; return fun(num[n], calc(n+1), op[n]) ; } num[n+1] = fun(num[n], num[n+1], op[n]) ; return calc(n+1) ;}double gao(){ cnt = 0 ; getWord() ; return calc(0) ; ;}int main (){ while (gets(str) && strcmp (str, "0")) printf ("%.2lf\n", gao()) ; return 0 ;}
来源:https://www.cnblogs.com/lzsz1212/archive/2012/01/06/2315349.html