-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc.c
More file actions
106 lines (94 loc) · 2.15 KB
/
calc.c
File metadata and controls
106 lines (94 loc) · 2.15 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
106
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef enum {ADD, SUBTRACT, MULTIPLY, DIVIDE} operators;
int isOperator(char *arg);
operators determineOperation(char operation);
struct Expression{
int operandLeft;
int operandRight;
operators operator;
};
struct Expression *Expression_create(int operandLeft, int operandRight, operators operator)
{
struct Expression *expression = malloc(sizeof(struct Expression));
expression->operandLeft = operandLeft;
expression->operandRight = operandRight;
expression->operator = operator;
return expression;
}
void Expression_destroy(struct Expression *expression){
assert(expression != NULL);
free(expression);
}
int Expression_operate(struct Expression *expression)
{
switch(expression->operator) {
case ADD:
return(expression->operandLeft + expression->operandRight);
break;
case SUBTRACT:
return(expression->operandLeft - expression->operandRight);
break;
case MULTIPLY:
return(expression->operandLeft * expression->operandRight);
break;
case DIVIDE:
return(expression->operandLeft / expression->operandRight);
break;
default:
return(0);
}
}
int main(int argc, char *argv[])
{
int i = 1;
char operation = ' ';
int opFlag = 0;
int left = 0;
int right = 0;
int result = 0;
for(i = 1; i < argc; i++) {
opFlag = isOperator(argv[i]);
if(opFlag == 1) {
operation = *argv[i++];
right = atoi(argv[i]);
struct Expression *expression = Expression_create(left, right, determineOperation(operation));
result = Expression_operate(expression);
printf("%d\n", result);
Expression_destroy(expression);
} else {
left = atoi (argv[i]);
}
}
return 0;
}
int isOperator(char *arg)
{
if(*arg == 43 || *arg == 45 || *arg == 120 || *arg == 47) {
return 1;
} else {
return 0;
}
}
operators determineOperation(char operation)
{
switch(operation) {
case '+':
return(ADD);
break;
case '-':
return(SUBTRACT);
break;
//Cannot use '*' because shells reserve that character. There might be a workaround?
case 'x':
return(MULTIPLY);
printf("Made it here");
break;
case '/':
return(DIVIDE);
break;
default:
return(ADD);
}
}