Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <mylib.c>
- #include <math.h>
- #define MAXOP 100
- #define NUMBER '0'
- #define BUFSIZE 100
- char buf[BUFSIZE];
- int bufp = 0;
- int sp = 0; /* next free stack position */
- /* get a (possibly pushed back) character, */
- int
- getch(void)
- {
- return (bufp > 0) ? buf[--bufp] : getchar();
- }
- /* push character back to input */
- void ungetch(int c)
- {
- if(bufp >= BUFSIZE)
- printf("ungetch: to many characters\n");
- else
- buf[bufp++] = c;
- }
- // PUSH & POP
- #define MAXVAL 100 /* maximum depth of val stack */
- double val[MAXVAL]; /* value stack */
- /* push on top of the stack*/
- void
- push(double f)
- {
- if(sp < MAXVAL)
- val[sp++] = f;
- else
- printf("error: stack if full, can't push %g\n", f);
- }
- /* extract end return a value on top of the stack*/
- double
- pop(void)
- {
- if(sp > 0)
- return val[--sp];
- else
- {
- printf("error: stack is empty\n");
- return 0.0;
- }
- }
- /*
- get next operator or numeric operand
- */
- int
- getop(char s[])
- {
- int i, c;
- while((s[0] = c = getch()) == ' ' || c == '\t')
- ;
- s[1] = '\0';
- if(!isDigit(c) && c != '.' && c != '-')
- return c; // is not a number or a minus
- i = 0;
- if (c == '-')
- {
- if((!isdigit(c = getch()) && c != '.'))
- {
- ungetch(c);
- return '-';
- }
- else if (c == '.')
- {
- s[++i] = c;
- }
- else
- ungetch(c);
- }
- if(isDigit(c)) // collect integer part
- while(isDigit(s[++i] = c = getch()))
- ;
- if(c == '.') // collect fraction part
- while(isDigit(s[++i] = c = getch()))
- ;
- s[i] = '\0';
- if(c != EOF)
- ungetch(c);
- return NUMBER;
- }
- /*
- reverse polish calculator
- */
- 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 : division by zero\n");
- break;
- case '%':
- op2 = pop();
- if(op2 != 0.0)
- push(fmod(pop() , op2));
- else
- printf("error : division by zero\n");
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: command unknown %s\n", s);
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement