Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <math.h>
- int eval(char **_s);
- int feed_signed_operand(char **_s);
- int feed_num(char **_s)
- {
- char *s = *_s;
- int num = 0;
- while (isdigit(*s))
- {
- num = num * 10 + *s - '0';
- s++;
- }
- *_s = s;
- return num;
- }
- int feed_single_operand(char **_s)
- {
- char *s = *_s;
- int num = 0;
- if (*s == '(')
- {
- s++;
- num = eval(&s);
- if (*s == ')')
- s++;
- else {
- printf("missing ) at %s\n", s);
- exit(0);
- }
- }
- else if (isdigit(*s))
- num = feed_num(&s);
- else {
- printf("error at %s\n", s);
- exit(0);
- }
- *_s = s;
- return num;
- }
- int feed_powered_operand(char **_s)
- {
- char *s = *_s;
- int num = 0;
- num = feed_single_operand(&s);
- if (*s == '^')
- {
- int num2;
- s++;
- num2 = feed_signed_operand(&s);
- num = (int) pow(num, num2);
- }
- *_s = s;
- return num;
- }
- int feed_signed_operand(char **_s)
- {
- char *s = *_s;
- int multBy = 1, num = 0;
- while (*s == '-' || *s == '+')
- {
- if (*s == '-')
- multBy *= -1;
- s++;
- }
- num = feed_powered_operand(&s);
- num *= multBy;
- *_s = s;
- return num;
- }
- int feed_mul_dip_expr(char **_s)
- {
- char *s = *_s;
- int num;
- int res = 1;
- char c = 0;
- while (1)
- {
- num = feed_signed_operand(&s);
- if (c == '*' || c == 0)
- res *= num;
- else if (c == '/')
- res /= num;
- if (*s == '*' || *s == '/')
- c = *s++;
- else
- break;
- }
- *_s = s;
- return res;
- }
- int eval(char **_s)
- {
- char *s = *_s;
- int num;
- int res = 0;
- char c = 0;
- while (1)
- {
- num = feed_mul_dip_expr(&s);
- if (c == '+' || res == 0)
- res += num;
- else if (c == '-')
- res -= num;
- if (*s == '+' || *s == '-')
- c = *s++;
- else
- break;
- }
- *_s = s;
- return res;
- }
- int main()
- {
- #define E "-22/-11+2^3*2^(1+2^((-1+3)*2))"
- //#define E "-(2^(-++-1))"
- char buff[10000],*s;
- int res;
- strcpy(buff, E);
- s = buff;
- res = eval(&s);
- printf("%s = %d\n", buff, res);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement