Path: blob/master/languages/cprogs/Ex_4.4_rpn_top_two_elements.c
1240 views
/* Add commands to1- print top element of the stack,without poping2- duplicate it3- swap the top two elements4- Clear the stack */56#include<stdio.h>7#include<stdlib.h>8#include<math.h>910#define MAXOP 10011#define NUMBER '0'1213int getop(char []);14void push(double);15double pop(void);1617/* reverse polish calculator */1819int main(void)20{21int type;22double op2,op1;23char s[MAXOP];24void clearsp(void);2526while((type = getop(s)) != EOF)27{28switch(type)29{30case NUMBER:31push(atof(s));32break;33case '+':34push(pop()+pop());35break;36case '*':37push(pop()*pop());38break;39case '-':40op2 = pop();41push(pop()-op2);42break;43case '/':44op2 = pop();45if(op2 != 0.0)46push(pop()/op2);47else48printf("error:zero divisor\n");49break;50case '%':51op2 = pop();52if(op2 != 0.0)53push(fmod(pop(),op2));54else55printf("erro:zero divisor\n");56break;57case '?':58op2=pop();59printf("\t%.8g\n",op2);60push(op2);61break;62case 'c':63clearsp();64break;65case 'd':66op2=pop();67push(op2);68push(op2);69break;70case 's':71op1=pop();72op2=pop();73push(op1);74push(op2);75break;76case '\n':77printf("\t%.8g\n",pop());78break;79default:80printf("error: unknown command %s\n",s);81break;82}83}84return 0;85}868788#define MAXVAL 1008990int sp = 0;91double val[MAXVAL];9293void push(double f)94{95if(sp < MAXVAL)96val[sp++]=f;97else98printf("error:stack full, cant push %g\n",f);99}100101102double pop(void)103{104if(sp>0)105return val[--sp];106else107{108printf("error: stack empty\n");109return 0.0;110}111}112113void clearsp(void)114{115sp = 0;116}117118#include<ctype.h>119120int getch(void);121void ungetch(int);122123int getop(char s[])124{125int i,c;126127while((s[0] = c = getch()) == ' ' || c =='\t')128;129s[1] = '\0';130131i = 0;132if(!isdigit(c) && c!='.' && c!='-')133return c;134135if(c=='-')136if(isdigit(c=getch()) || c == '.')137s[++i]=c;138else139{140if(c!=EOF)141ungetch(c);142return '-';143}144145if(isdigit(c))146while(isdigit(s[++i] =c =getch()))147;148149if(c=='.')150while(isdigit(s[++i] = c=getch()))151;152153s[i] = '\0';154if(c!=EOF)155ungetch(c);156return NUMBER;157}158159#define BUFSIZE 100160161char buf[BUFSIZE];162int bufp = 0;163164int getch(void)165{166return (bufp > 0) ? buf[--bufp] : getchar();167}168169void ungetch(int c)170{171if(bufp >= BUFSIZE)172printf("ungetch: too many characters\n");173else174buf[bufp++] = c;175}176177178179