Newer
Older
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
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
# define LEN(x) (sizeof(x) / sizeof(*x))
enum Product { COFFE = 0, TEA = 1, CHOCOLATE = 2, CAPPUCCINO = 3, LAST_PRODUCT };
const char *const products_str[] = { "caffe'", "the", "cioccolata", "cappuccino", };
const int products_price[] = { 50, 40, 60, 70 };
const int coins[] = { 1, 5, 10, 20, 50 };
void print_numbered_strings(const char *const products[], size_t len) {
for (size_t i = 0; i < len; ++i) {
printf("%zu. %s\n", i, products[i]) ;
}
}
int input_int() {
int ret;
scanf("%d", &ret);
return ret;
}
int input_int_range(int lower, int upper) {
int ret;
while ((ret = input_int()) < lower || ret > upper) {
puts("Valore non ammesso");
}
return ret;
}
bool is_in_array(int needle, const int haystack[], size_t len) {
bool found = false;
// could use memmem(3) instead
for (size_t i = 0; i < len && !found; i++) {
if (haystack[i] == needle) { found = true; }
}
return found;
}
int input_int_filter(const int whitelist[], size_t len) {
int ret;
while (ret = input_int(), !is_in_array(ret, whitelist, len)) {
puts("Valore non ammesso");
}
return ret;
}
void calculate_change(int total, int *count_5, int *count_1) {
*count_5 = total / 5;
total -= 5 * *count_change;
*count_1 = total;
}
int main(void) {
assert(LEN(products_str) == LEN(products_price));
assert(LEN(products_str) == LAST_PRODUCT);
int selected_product;
int credit = 0;
int inserted_coin;
int count_change_5 = 0, count_change_1 = 0;
puts("Seleziona il prodotto");
print_numbered_strings(products_str, LEN(products_str));
selected_product = input_int_range(0, LAST_PRODUCT);
printf("Costo: %d centesimi\n", products_price[selected_product]);
puts("Inserisci monete");
while (credit < products_price[selected_product]) {
inserted_coin = input_int_filter(coins, LEN(coins));
credit += inserted_coin;
}
calculate_change(
credit - products_price[selected_product],
&count_change_5, &count_change_1
);
printf("Resto: %d monete da 5, %d monete da 1\n", count_change_5, count_change_1);
return 0;
}