Advertisement
a3f

simple extensible calculator

a3f
Oct 6th, 2014
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. // TODO: Check return val of scanf()
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <stdlib.h>
  5.  
  6. #define ARRAY_SIZE(x) (sizeof(x)/sizeof (x)[0])
  7. #define CLEAR_STDIN do {} while ( (c = getchar()) != '\n' && c != EOF )
  8.  
  9. double _sum(double x, double y) { return x + y;}
  10. double _sub(double x, double y) { return x - y;}
  11. double _mul(double x, double y) { return x * y;}
  12. double _div(double x, double y) { return x / y;}
  13. double _curt(double x) { return pow(x, 1.f / 3);}
  14. double _quit(void) { exit(0); return 0;}
  15.  
  16. struct
  17. {
  18.     const char *description;
  19.     const char *symbol;
  20.     int operands;
  21.     double (*function)();
  22. } ops[] = {{"sum", "+", 2, _sum}    ,{"sub", "-", 2, _sub}
  23.       ,{"mul", "*", 2, _mul}    ,{"div", "/", 2, _div}
  24.       ,{"pow", "^", 2, pow} ,{"abs", " ", 1, fabs}
  25.       ,{"sqrt", "√", 1, sqrt},{"curt", "∛", 1, _curt}
  26.        {"exit", "⎋", 0, _quit}
  27. };
  28.  
  29.  
  30. int main (void)
  31. {
  32.     int i, c;
  33.     printf("****\n");
  34.     for (i = 0; i < ARRAY_SIZE(ops); i++){
  35.         printf("%d- %s (%s)", i + 1, ops[i].description, ops[i].symbol);
  36.        
  37.         if (i % 2)  printf("\n");
  38.         else        printf("\t\t\t\t\t");
  39.     }
  40.    
  41.     unsigned choice;
  42.     double x,y;
  43.     for (;;){
  44.         printf("\n****\nSelect:  ");
  45.         scanf("%u", &choice); choice--;
  46.         CLEAR_STDIN;
  47.         if (choice > i){
  48.             printf ("Invalid; try again.");
  49.             continue;
  50.         }
  51.         switch (ops[choice].operands){
  52.         case 0: // constant or x(void) function
  53.             printf("=%lg", ops[choice].function());
  54.         break;
  55.         case 1: // function with 1 parameter
  56.             printf("Enter Number: ");
  57.             scanf("%lf", &x);
  58.             printf("%s(%lg) = %lg", ops[choice].description, x, ops[choice].function(x));
  59.         break;
  60.         case 2: // function with 2 parameters
  61.             printf("Enter Number 1: ");
  62.             scanf("%lf", &x);
  63.             printf("Enter Number 2: ");
  64.             scanf("%lf", &y);
  65.             printf("%lg %s %lg = %lg", x,ops[choice].symbol, y,ops[choice].function(x,y));
  66.         break;
  67.         }
  68.     }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement