Skip to content

Instantly share code, notes, and snippets.

@d630
Last active May 24, 2018 16:31
Show Gist options
  • Save d630/72a38488a069d616bce5e0117ee79556 to your computer and use it in GitHub Desktop.
Save d630/72a38488a069d616bce5e0117ee79556 to your computer and use it in GitHub Desktop.
Getränkeding
#include <stdio.h>
#include <stdlib.h>
#define LEN(arr) ((int) (sizeof(arr) / sizeof(arr)[0]))
#define PREIS_TO_INT(arr, adr, row) ((int) strtol(arr[row][1], adr, 10))
#define NAME 0
#define PREIS 1
static const char *getraenk[][2] = {
{ "Cola", "120" },
{ "Fanta", "130" },
{ "Sprite", "150" },
{ "H20", "140" }
};
static const int muenze[] = {
1,
2,
5,
10,
20,
50,
100,
200,
500
};
static const int selection(void);
static const void print_menu(void);
static const int find_price(int);
static const void deal(int);
static const int pay(void);
static const void payback(int);
static const void deliver(int);
int selection(void)
{
int auswahl;
while (1) {
printf("Select: ");
scanf("%d", &auswahl);
if (auswahl == 0) {
puts("Bye-bye!");
exit(0);
} else if (auswahl - 1 < 0 || auswahl - 1 >= LEN(getraenk)) {
puts("Such an idiot ...");
} else {
printf("You've chosen %s.\n", getraenk[auswahl - 1][NAME]);
break;
}
}
return auswahl - 1;
}
void print_menu(void)
{
int i;
char *c = NULL;
puts("Thirsty?");
puts("--------");
for (i = 0; i < LEN(getraenk); i++)
printf("%2d %10.10s %3d\n",
(i + 1),
getraenk[i][NAME],
PREIS_TO_INT(getraenk, &c, i));
printf("%2d %10.10s\n", 0, "Exit");
}
int find_price(int gewaehlt)
{
char *c = NULL;
int p = PREIS_TO_INT(getraenk, &c, gewaehlt);
printf("%s costs %d.\n", getraenk[gewaehlt][NAME], p);
return p;
}
void deal(int preis)
{
do {
printf("Still to give: %d\n", preis);
preis -= pay();
} while (preis > 0);
if (preis < 0)
payback(preis * -1);
}
int pay(void)
{
int einwurf;
while (1) {
printf("Input: ");
scanf("%d", &einwurf);
for (int i = 0; i < LEN(muenze); i++) {
if (einwurf == muenze[i]) {
printf("You've put in %d.\n", einwurf);
return einwurf;
}
}
puts("What kind of coin is it? It's wrong. Really.");
}
}
void payback(int preis)
{
printf("Your change: %d\n", preis);
puts("Please collect:");
for (int i = LEN(muenze) - 1; i >=0; i--) {
printf("\t%2d x %3d\n", preis / muenze[i], muenze[i]);
preis %= muenze[i];
}
}
void deliver(int gewaehlt)
{
printf("Take your drink: %s.\n\n", getraenk[gewaehlt][NAME]);
}
int main(void)
{
int gewaehlt;
while (1) {
print_menu();
gewaehlt = selection();
deal(find_price(gewaehlt));
deliver(gewaehlt);
}
}
// vim: set ft=c :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment