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
| #include <stdio.h>
#include <stdlib.h>
int additioner(int n1,int n2, char *txt) {
int res=n1 + n2;
if (txt) sprintf(txt, "%d + %d = %d", n1, n2, res);
return res;
}
int soustraire(int n1,int n2, char *txt) {
int res=n1 - n2;
if (txt) sprintf(txt, "%d - %d = %d", n1, n2, res);
return res;
}
int multiplier(int n1,int n2, char *txt) {
int res=n1 * n2;
if (txt) sprintf(txt, "%d * %d = %d", n1, n2, res);
return res;
}
int diviser(int n1,int n2, char *txt) {
int res=n1 / n2; // ouch if n2 = 0.
if (txt) sprintf(txt, "%d / %d = %d", n1, n2, res);
return res;
}
typedef struct {
int (*op)(int, int, char*);
char lettre;
} t_operator;
int operation(t_operator *tab, char lettre, int n1, int n2, char *txt)
{
t_operator *pt;
for (pt=tab; pt->op != NULL; pt++)
if (pt->lettre == lettre) return ((pt->op)(n1, n2, txt));
if (txt) sprintf(txt, "%d %c %d: opération inconnue", n1, lettre, n2);
return 0;
}
int main() {
t_operator tabOp[]={
{additioner, '+'},
{soustraire, '-'},
{multiplier, '*'},
{diviser, '/'},
{NULL, '\0'},
};
char msg[512];
operation(tabOp, '+', 5, 3, msg);
printf("%s\n", msg);
operation(tabOp, '-', 5, 3, msg);
printf("%s\n", msg);
operation(tabOp, '*', 5, 3, msg);
printf("%s\n", msg);
operation(tabOp, '/', 5, 3, msg);
printf("%s\n", msg);
return EXIT_SUCCESS;
} |
Partager