-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
148 lines (128 loc) · 2.88 KB
/
main.cpp
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include <iostream>
#include "queue/queue.h"
/**
* Defines and typedefs
*/
#define NUMBERS_QTY 2
typedef enum {
INPUT,
OPERATION
}states_t;
/**
* Sums all numbers in the queue
*/
int sum(queue_t &q){
node_t *node = q.tail;
int sum = 0;
for(int i = 0; i < NUMBERS_QTY; i++){
sum += node->number;
node = node->prev;
}
return sum;
}
/**
* Substract last two numbers in the queue
*/
int substraction(queue_t &q){
node_t *node = q.tail;
return (node->prev->number - node->number);
}
/**
* Calculates the product of all numbers in the queue
*/
int product(queue_t &q){
node_t *node = q.tail;
int product = 1;
for(int i = 0; i < NUMBERS_QTY; i++){
product *= node->number;
node = node->prev;
}
return product;
}
/**
* Divides last two numbers in the queue
*/
float division(queue_t &q){
node_t *node = q.tail;
return ((float) node->prev->number / (float) node->number);
}
/**
* Performs Sum, Substraction, Product and Division on the last two elements
* in the given queue.
* @param q: Queue reference
* @param op: Operation to be executed.
* @param result: Stores the operation result
* @return True if successful, false otherwise (e.g., Unsupported operation).
*/
bool executeOperation(queue_t &q, char op, float &result){
bool res = true;
switch(op){
case '+':
result = sum(q);
break;
case '-':
result = substraction(q);
break;
case '*':
result = product(q);
break;
case '/':
result = division(q);
break;
default:
res = false;
break;
}
return res;
}
/**
* Application entrypoint
*/
int main(){
/**
* Queue defined
*/
queue_t q = {
.head = NULL,
.tail = NULL
};
/**
* State machine state
*/
states_t state = INPUT;
int numbersInserted = 0;
while(true){
/**
* States
*/
char temp;
int value;
float result;
char operation;
printf("> ");
switch (state){
case INPUT:
scanf("%i", &value);
scanf("%c", &temp);
addToQueue(q, value);
showLastInQueue(q);
numbersInserted++;
if (numbersInserted == NUMBERS_QTY){
numbersInserted = 0;
state = OPERATION;
}
break;
case OPERATION:
scanf("%c", &operation);
scanf("%c", &temp);
bool res = executeOperation(q, operation, result);
if(res)
printf("%.2f\n", result);
else
printf("Operation no valida \n");
state = INPUT;
break;
}
}
return 0;
}