-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathex2-1.c
83 lines (74 loc) · 1.48 KB
/
ex2-1.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
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int convert_to_int(char *argument){
int output = 0;
if(argument[0] == '0'){
if(argument[1] == 'x' || argument [1] == 'X'){
output = (int)strtol(argument, NULL, 16);
}
else{
output = (int)strtol(argument, NULL, 8);
}
}
else{
output = atoi(argument);
}
return output;
}
int main(int argc, char *argv[]){
char operator = *argv[1];
int result = 0;
if(argc < 4){
printf("Too few arguments");
return 1;
}
if(strlen(argv[1]) > 1){
printf("Operator should be a single character");
return 1;
}
switch(operator){
case '+':
result = convert_to_int(argv[2]);
for(int i = 3; i < argc; i++){
result += convert_to_int(argv[i]);
}
break;
case '-':
result = convert_to_int(argv[2]);
for(int i = 3; i < argc; i++){
result -= convert_to_int(argv[i]);
}
break;
case '*':
result = convert_to_int(argv[2]);
for(int i = 3; i < argc; i++){
result *= convert_to_int(argv[i]);
}
break;
case '/':
result = convert_to_int(argv[2]);
for(int i = 3; i < argc; i++){
int j = convert_to_int(argv[i]);
if(j != 0){
result /= convert_to_int(argv[i]);
}
else{
printf("Divide by zero!\n");
return 1;
}
}
break;
case '%':
result = convert_to_int(argv[2]);
for(int i = 3; i < argc; i++){
result %= convert_to_int(argv[i]);
}
break;
default:
printf("Invalid operator\n");
return 1;
}
printf("%d\n", result);
return 0;
}