diff options
Diffstat (limited to '5.6.4.c')
-rw-r--r-- | 5.6.4.c | 133 |
1 files changed, 133 insertions, 0 deletions
@@ -0,0 +1,133 @@ +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> +#include <math.h> + +#define MAXOP 100 +#define NUMBER_SIG '0' + +double pop(void); +void push(double f); +char getop(char str[]); + +int +main(void) +{ + char str[MAXOP]; + char type; + double op2; + + while ((type = getop(str)) != EOF) { + switch (type) { + case NUMBER_SIG : + push(atof(str)); + break; + case '+' : + push(pop() + pop()); + break; + case '*' : + push(pop() * pop()); + break; + case '-' : + op2 = pop(); + push(pop() - op2); + break; + case '/' : + if ((op2 = pop()) == 0.0) + printf("Err: deviser cant be zero\n"); + else + push(pop() / op2); + + break; + case '%' : + op2 = pop(); + if (op2 != 0) + push(fmod(pop(), op2)); + else + printf("Err: deviser cant be zero\n"); + + break; + case '\n' : + printf("%.8g\n", pop()); + break; + default : + printf("Err: unknown command\n"); + } + } + + return 0; +} + +#define MAXVAL 100 +double val[MAXVAL]; +int sp = 0; + +double +pop(void) +{ + if (sp > 0) + return val[--sp]; + else { + printf("Err: stack empty\n"); + return 0.0; + } +} + +void +push(double f) +{ + if (sp < MAXVAL) + val[sp++] = f; + else + printf("Err: stack is full\n"); +} + +char getch(void); +void ungetch(char input); + +char +getop(char str[]) +{ + char input, *str_og; + + str_og = str; + + /* ignore blanks */ + while (isblank(input = *str = getch())); + + /* return operator */ + if (!isdigit(input) && input != '.') + return input; + + /* collect digits*/ + while (str - str_og < MAXOP && (isdigit(input=getch()) || input == '.')) + *++str = input; + + *++str = '\0'; + + if (input != EOF) + ungetch(input); + + return NUMBER_SIG; +} + +#define MAXBUFF 100 +char buff[MAXBUFF]; +int bp = 0; + +char +getch(void) +{ + return (bp > 0) ? buff[--bp] : getchar(); +} + +void +ungetch(char input) +{ + if (bp < MAXBUFF) + buff[bp++] = input; + else { + printf("Err: buffer full\n"); + } +} + |