#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; }