Table Of Contents
Previous Section Next Section

Program 71: Unsynchronized

The assignment here is to make a four-function calculator. The user is supposed to type in an operator and a number, and the calculator goes to work. For example:

         Enter operator and value: + 10
         Total: 10

But things don't go as expected.

  1 /************************************************
  2  * calc -- Simple 4 function calculator.        *
  3  *                                              *
  4  * Usage:                                       *
  5  *      $ calc                                  *
  6  *      Enter operator and value: + 5           *
  7  *                                              *
  8  * At the end of each operation the acculated   *
  9  * results are printed.                         *
 10  ************************************************/
 11 #include <stdio.h>
 12 #include <stdlib.h>
 13 int main() {
 14     char oper;  /* Operator for our calculator */
 15     int  result;/* Current result */
 16     int value;  /* Value for the operation */
 17
 18     result = 0;
 19     while (1)
 20     {
 21         printf("Enter operator and value:");
 22         scanf("%c %d", &oper, &value);
 23
 24         switch (oper) {
 25             case '+':
 26                 result += value;
 27                 break;
 28             case '-':
 29                 result -= value;
 30                 break;
 31             case '*':
 32                 result *= value;
 33                 break;
 34             case '/':
 35                 if (value == 0)
 36                     printf("Divide by 0 error\n");
 37                 else
 38                     result /= value;
 39                 break;
 40             case 'q':
 41                 exit (0);
 42             default:
 43                 printf("Bad operator entered\n"); break;
 44         }
 45         printf("Total: %d\n", result);
 46     }
 47 }

(Next Hint 224. Answer 28.)

Table Of Contents
Previous Section Next Section