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
|
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#include <signal.h>
/* ##############################################
Initialisation librairie ncurses
############################################## */
void initNcurses()
{
initscr();
noecho();
}
typedef struct _Structure {
int *liste;
int sizeMax;
int size;
int position;
double moyenne;
} Structure;
Structure list;
Structure constructorStructure(int sizeMax) {
Structure s;
s.sizeMax = sizeMax;
s.liste = malloc(sizeof(int)*sizeMax);
s.size = 0;
s.position = 0;
s.moyenne = 0;
if (s.liste == NULL)
{
printf("Erreur allocation\n");
endwin();
exit(EXIT_FAILURE);
}
return s;
}
void push(Structure* ptr, int elem)
{
if (ptr->size < ptr->sizeMax) {
ptr->liste[ptr->position] = elem;
ptr->position++;
ptr->size++;
ptr->moyenne += elem / (double)ptr->sizeMax;
}
else {
ptr->position %= ptr->sizeMax;
ptr->moyenne -= ptr->liste[ptr->position] / (double)ptr->sizeMax;
ptr->moyenne += elem / (double)ptr->sizeMax;
ptr->liste[ptr->position] = elem;
ptr->position++;
}
}
void loop(Structure* s)
{
int newElement;
int delindex;
char str[256];
while(1)
{
refresh();
newElement = (int)(rand()/(float)RAND_MAX * 0x0A) + 1;
move(1,0);
sprintf(str,"Ajout d'un nombre:%02d", newElement);
addstr(str);
if (newElement >= 1 && newElement <= 10)
{
push(s, newElement);
move(2,0);
sprintf(str,"Moyenne obtenue:%02.2f", s->moyenne);
addstr(str);
}
else
{
printf("Il y a un bug sur ce programme.\n\r");
endwin();
exit(EXIT_FAILURE);
}
refresh();
sleep(1);
}
}
void destructorStructure(Structure* s)
{
free(s->liste);
}
void quit(int i)
{
move(5,0);
addstr("Fin du programme\n\r");
refresh();
endwin();
destructorStructure(&list);
exit(EXIT_SUCCESS);
}
int main(int argc, char **argv)
{
int sizeMax;
printf("argc=%d\n",argc);
if (argc < 2) {
printf("USAGE : moyenne sizeMax\n\r");
return EXIT_SUCCESS;
} else {
sizeMax = atoi(argv[1]);
if (sizeMax > 0)
{
initNcurses();
refresh();
signal(SIGINT, quit);
printf("Calcul de la moyenne sur une plage de valeurs de %d\n\r",sizeMax);
printf("Appuyez sur CTRL+C pour terminer\n\r");
list = constructorStructure(sizeMax);
loop(&list);
destructorStructure(&list);
} else {
printf("Erreur : sizeMax n'a pas la bonne valeur\n\r");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
} |
Partager