1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
思路:
可以用动态规划的思路来做。保存两个数和中间的计算符,逐步向后推进即可。
据说用栈做这个题效果也不错。
代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #define M 200 int isnumber(char c) { return ('0' <= c && c <= '9'); } double compute(double a, char op, double b) { switch(op) { case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } } void combine(double *a, char *op, double *b, char opnew, double c) { if (opnew == '+' || opnew == '-') { *a = compute(*a, *op, *b); *op = opnew; *b = c; } else *b = compute(*b, opnew, c); } int main(void) { char s[M+1], tmp[M+1]; int i, j; double a, b, c; char op, opnew; double res; while (gets(s)) { if (strcmp(s, "0") == 0) break; a = 0.0; b = 0.0; op = '+'; i = 0; while (s[i]) { if (i != 0) { i++; opnew = s[i++]; i++; } else opnew = '+'; j = 0; while (isnumber(s[i])) tmp[j++] = s[i++]; tmp[j] = '\0'; c = atoi(tmp); combine(&a, &op, &b, opnew, c); } res = compute(a, op, b); printf("%.2lf\n", res); } return 0; } /************************************************************** Problem: 1019 User: liangrx06 Language: C Result: Accepted Time:0 ms Memory:912 kb ****************************************************************/