From 2af28ad897671a1c6a46d64b06ac1887c35ad7b5 Mon Sep 17 00:00:00 2001 From: Steven Schronk Date: Tue, 15 Dec 2009 22:31:54 -0600 Subject: [PATCH] Advanced calculator now supports modulus. --- calc_adv.c | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 calc_adv.c diff --git a/calc_adv.c b/calc_adv.c new file mode 100644 index 0000000..daddccd --- /dev/null +++ b/calc_adv.c @@ -0,0 +1,129 @@ +#include +#include +#include + +#define MAXOP 100 +#define NUMBER '0' +#define MAXVAL 100 +#define BUFSIZE 100 + +int getop(char[]); +void push(double); +double pop(void); + +int main() +{ + int type; + double op2; + char s[MAXOP]; + + while((type = getop(s)) != EOF) + { + switch(type) + { + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if(op2 != 0.0) + push(pop() / op2); + else + printf("error: zero divisor\n"); + break; + case '%': + op2 = pop(); + if(op2 != 0.0) + { + push((int)(pop()) % (int)(op2)); + } else { + printf("error: zero divisor\n"); + } + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; + } + } + return 0; +} + +int sp = 0; +double val[MAXVAL]; + +/* push f onto value stack */ +void push(double f) +{ + if(sp < MAXVAL) + val[sp++] = f; + else + printf("error: stack full\n"); +} + + +/* pop and return top value from stack */ +double pop(void) +{ + if(sp > 0) + return val[--sp]; + else + { + printf("error: stack empty\n"); + return 0.0; + } +} + +int getch(void); +void ungetch(int); + +/* get next operator or numberic operand */ +int getop(char s[]) +{ + int i, c; + + while ((s[0] = c = getch()) == ' ' || c == '\t') + ; + s[1] = '\0'; + if(!isdigit(c) && c != '.') + return c; + i = 0; + if(isdigit(c)) + while(isdigit(s[++i] = c = getch())) + ; + if(c == '.') + while(isdigit(s[++i] = c = getch())) + ; + s[i] = '\0'; + if(c != EOF) + ungetch(c); + return NUMBER; +} + +char buf[BUFSIZE]; +int bufp = 0; + +int getch(void) +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) +{ + if(bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} -- 2.11.4.GIT