#include #include #include #define MAXOP 100 #define NUMBER '0' #define NAME 'n' #define MAXVAL 100 #define MAXLINE 100 #define PI 3.14159265358979323846 int sp=0; double val[MAXVAL]; int li=0; char line[MAXLINE]; int getop(char []); void push(double); double pop(void); void mathfnc(char []); int getline(char line[],int limit); main() { int i,type,var=0; double op1,op2; char s[MAXOP]; double variable[26]; for (i=0;i<26;i++) variable[i]=0.0; while ((type=getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case NAME: mathfnc(s); break; case '+': push(pop()+pop()); break; case '-': op2=pop(); push(pop()-op2); break; case '*': push(pop()*pop()); 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(fmod(pop(),op2)); else printf("error: zero divisor\n"); break; case '=': pop(); if (var>='A' && var<='Z') variable[var - 'A']=pop(); else printf("error: no variable name\n"); break; case 'q': exit (0); case '\n': printf("\t%.8g\n",pop()); break; case '?': op2=pop(); printf("\t%.8g\n",op2); push(op2); break; default: printf("error: unknown command %s\n",s); break; } } return 0; } int getline(char s[],int lim) { int c,i; i=0; while (--lim > 0 && (c=getchar()) != EOF && c !='\n') s[i++]=c; if (c=='\n') s[i++]=c; s[i]='\0'; return i; } void push(double f) { if (sp0) return val[--sp]; else { printf("error: stack empty\n"); return 0.0; } } int getop(char s[]) { int c,i; if (line[li]=='\0') if (getline(line,MAXLINE)==0) return EOF; else li=0; while ((s[0]=c=line[li++])==' ' || c=='\t') ; s[1]='\0'; i=0; if (islower(c)) { while (islower(s[++i] = c = line[li++])) ; s[i]='\0'; if (strlen(s)>1) return NAME; else return c; } if (!isdigit(c) && c!='.') return c; if (isdigit(c)) while (isdigit(s[++i]=c=line[li++])) ; if (c=='.') while (isdigit(s[++i]=c=line[li++])) ; s[i]='\0'; li--; return NUMBER; } void mathfnc(char s[]) { double op2; if (strcmp(s,"sin")==0) push(sin(pop())); else if (strcmp(s,"cos")==0) push(cos(pop())); else if (strcmp(s,"tan")==0) push(tan(pop())); else if (strcmp(s,"pow")==0) { op2=pop(); push(pow(pop(),op2)); } else if (strcmp(s,"quit")==0) exit (0); else if (strcmp(s,"asin")==0) push(asin(pop())); else if (strcmp(s,"acos")==0) push(acos(pop())); else if (strcmp(s,"atan")==0) push(atan(pop())); else if (strcmp(s,"cosh")==0) push(cosh(pop())); else if (strcmp(s,"sinh")==0) push(sinh(pop())); else if (strcmp(s,"tanh")==0) push(tanh(pop())); else if (strcmp(s,"exp")==0) push(exp(pop())); else if (strcmp(s,"log")==0) push(log10(pop())); else if (strcmp(s,"ln")==0) push(log(pop())); else if (strcmp(s,"sqrt")==0) push(sqrt(pop())); else if (strcmp(s,"pi")==0) push(PI); else if (strcmp(s,"rot")==0) push(1 / (pop())); else if (strcmp(s,"chs")==0) push(-1*pop()); else printf("error: %s not supported\n",s); }