#include #include /* for atof() */ #include /* for atof() */ #include "calc.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_E #define M_E 2.718281828459045235360287 #endif #define MAXOP 100 /* max size of operand or operator */ static int dostr( int type, char *s); void help() { fprintf(stderr,"\n+,*,-,/,h,;=top to console\n"); fprintf(stderr,"e=power: p =pop to console\n"); fprintf(stderr,"s sin, c cos, t tan\n"); fprintf(stderr,"S asin, C acos, T atan, q quit\n"); fprintf(stderr,"N clear stack,V print stack\n"); fprintf(stderr,"E=push exp1, P= push PI\n\n"); fprintf(stderr,"Example: sen(sqrt(3*3+1)*3.5*PI/2) =\n"); fprintf(stderr," 3 3 x 1 + 0.5 e 3.5 P x x 2 / s p\n"); } /* reverse Polish calculator */ int main( int argc, char **argv) { int i=0; int type=0; char s[MAXOP]; if ( argc==1 ) { while ((type = getop(s)) != EOF) { dostr ( type, s ); } } else { while ( ++i < argc ) { dostr ( sgetop(argv[i]), argv[i] ); } } return 0; } static int dostr( int type, char *s) { double op2; switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': case 'x': push(pop() * pop()); break; case '-': op2 = pop ( ); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else fprintf(stderr, "error: divisor is zero\n"); break; case 'e': op2 = pop(); push(pow(pop() , op2)); break; case 's': push(sin(pop())); break; case 'c': push(cos(pop())); break; case 't': push(tan(pop())); break; case 'T': push(atan(pop())); break; case 'C': push(acos(pop())); break; case 'S': push(asin(pop())); break; case 'E': push(M_E); break; case 'P': push(M_PI); break; case 'v': case ';': op2=pop();push(op2); printf(FORMATO_FL, op2); break; case 'V': PrintStack(); break; case 'p': printf(FORMATO_FL, pop()); break; case 'N': ClearStack(); break; case 'h': help(); break; case '\n': break; case 'q': exit(0); break; default: fprintf(stderr, "error: unknown command \"%s\"\n", s); break; } return 0; }