home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_100 / 154_01 / calc.c < prev    next >
Text File  |  1979-12-31  |  1KB  |  75 lines

  1. /*
  2.     calc.c:        simple display accumulator for quick,
  3.                 on-screen calculations.
  4.  
  5.     It accepts simple commands of the form  "x opr",
  6.     where "x" is a double, and "opr" is one of:
  7.  
  8.         s ==>    reset accumulator with number
  9.         + ==>    add number to accumulator
  10.         - ==>    subtract number from accumulator
  11.         * ==>    multiply accumulator by number
  12.         / ==>    divide accumulator by number (checks for 0)
  13.         q ==>     end session (or ^Z)
  14.  
  15.     Example:    10 s        (10.0000)
  16.                 5 +            (15.0000)
  17.                 3 /            ( 3.0000)
  18.                 0 e            (exit)
  19.  
  20. -----
  21.     (c) Chuck Allison, 1985
  22. -----
  23.  
  24. */
  25.  
  26. #include <stdio.h>
  27.  
  28. main()
  29. {
  30.     double     accum = 0.0,
  31.             x;
  32.     char    line[80],
  33.             opr;
  34.     int        argc;
  35.  
  36.     while (gets(line) != NULL)
  37.     {
  38.         argc = sscanf(line," %lf%1s",&x,&opr);
  39.         if (argc != 2)
  40.         {
  41.             /* ..invalid entry (probably backwards).. */
  42.             printf("? try again ..\n");
  43.             continue;
  44.         }
  45.         switch(opr)
  46.         {
  47.             case '+':
  48.                 accum += x;
  49.                 break;
  50.             case '-':
  51.                 accum -= x;
  52.                 break;
  53.             case '*':
  54.                 accum *= x;
  55.                 break;
  56.             case '/':
  57.                 if (x != 0)
  58.                     accum /= x;
  59.                 else
  60.                     printf("? division by 0: ");
  61.                 break;
  62.             case 's':
  63.             case 'S':
  64.                 accum = x;
  65.                 break;
  66.             case 'q':
  67.             case 'Q':
  68.                 exit(0);
  69.             default :
  70.                 printf("? invalid operator: ");
  71.         }
  72.         printf("%11.4f %c\n =%11.4f\n",x,opr,accum);
  73.     }
  74. }
  75.