- #include <assert.h>
- #include <stdio.h>
-
- int cal(int c1, char op, int c2)
- {
- if (op=='+') return c1+c2;
- if (op=='-') return c1-c2;
- if (op=='*') return c1*c2;
- if (op=='/') return c1/c2;
- return 0;
- }
-
- int calculate(int len, char *expStr)
- {
- assert(expStr);
- if (len < 3) return -1;
- char *p = expStr;
- int c1 = p[0]-'0';
- char op = p[1];
- int c2 = p[2]-'0';
- p += 3;
- while(*p) {
- if (*p=='*' || *p=='/') {
- c2 = cal(c2, *p, p[1]-'0');
- } else {
- c1 = cal(c1, op, c2);
- op = *p;
- c2 = p[1]-'0';
- }
- p += 2;
- }
- return cal(c1, op, c2);
- }
-
- int main(void) {
- int ret1 = calculate(3, "1+2");
- int ret2 = calculate(11, "1+2*3/5-6*7");
- int ret3 = calculate(11, "1+2-3/5-6*7");
- printf ("values: %d, %d, %d", ret1, ret2, ret3);
-
- return 0;
- }
-
-
-
|