-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc1.c
executable file
·48 lines (41 loc) · 1.3 KB
/
calc1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* example 7-1, pg 100 */
#include <stdio.h>
char line[100]; /* line of data from the input */
int result; /* the result of the calculations */
char operat; /* the operator the user specified */
int value; /* value specified after the operator */
int main()
{
result = 0; /* initialize the result */
/* loop forever (or until we hit the break statement */
while (1) {
printf("Result: %d\n", result);
printf("Enter operator and number: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%c %d", &operat, &value);
if ((operat == 'q') || (operat == 'Q')) {
break;
}
if (operat == '+') {
result += value;
}
else if (operat == '-') {
result -= value;
}
else if (operat == '*') {
result *= value;
}
else if (operat == '/') {
if (value == 0) {
printf("Error: cannot divide by zero\n");
printf("operation ignored\n");
}
else
result /= value;
}
else {
printf("Unknown operator %c\n", operat);
}
}
return (0);
}