-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path007-calculator.c
More file actions
105 lines (89 loc) · 1.96 KB
/
Copy path007-calculator.c
File metadata and controls
105 lines (89 loc) · 1.96 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdint.h>
#define OP_LEN 3
void calculate(const char *operator, double left, double right);
int main()
{
char *operator, *ptr;
double left, right;
operator = malloc(OP_LEN);
if (!operator)
{
fprintf(stderr, "Could not allocate %hu bytes of memory\n", OP_LEN);
abort();
}
while (1)
{
fputs("Enter the left operand: ", stdout);
scanf("%lf", &left);
fflush(stdin);
fputs("Enter the operator: ", stdout);
fgets(operator, OP_LEN, stdin);
ptr = strchr(operator, '\n');
if (ptr)
*ptr = '\0';
fputs("Enter the right operand: ", stdout);
scanf("%lf", &right);
calculate(operator, left, right);
}
free(operator);
return 0;
}
void calculate(const char *operator, double left, double right)
{
fputs("Result: ", stdout);
if (!strcmp(operator, "+"))
{
printf("%lf\n", left + right);
return;
}
if (!strcmp(operator, "-"))
{
printf("%lf\n", left - right);
return;
}
if (!strcmp(operator, "*"))
{
printf("%lf\n", left * right);
return;
}
if (!strcmp(operator, "/"))
{
if (!right)
{
puts("Division by zero");
return;
}
printf("%lf\n", left / right);
return;
}
if (!strcmp(operator, "%"))
{
if (!right)
{
puts("Modulo by zero");
return;
}
printf("%lf\n", fmod(left, right));
return;
}
if (!strcmp(operator, "//"))
{
if (!right)
{
puts("Division by zero");
return;
}
printf("%lld\n", (int64_t)(left / right));
return;
}
if (!strcmp(operator, "**"))
{
printf("%lf\n", pow(left, right));
return;
}
puts("Invalid operation");
}