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 accumulated *
9 * results are printed. *
10 ************************************************/
11 #include <stdio.h>
12 int main() {
13 char oper; /* Operator for our calculator */
14 int result;/* Current result */
15 int value; /* Value for the operation */
16
17 result = 0;
18 while (1)
19 {
20 char line[100]; // Line from the user
21 printf("Enter operator and value:");
22
23 fgets(line, sizeof(line), stdin);
24 sscanf(line, "%c %d", oper, value);
25
26 switch (oper) {
27 case '+':
28 result += value; break;
29 case '-':
30 result -= value; break;
31 case '*':
32 result *= value; break;
33 case '/':
34 if (value == 0)
35 printf("Divide by 0 error\n");
36 else
37 result /= value;
38 break;
39 case 'q':
40 exit (0);
41 default:
42 printf("Bad operator entered\n"); break;
43 }
44 printf("Total: %d\n", result);
45 }
46 }