Reputation: 23
I am a beginner in programming and i have been stuck on the following issue for a couple of days now.
I am rewriting this piece of code i created, by using 'functions' only. Note that in the execution of the original, we have the average coffee consumption of the programmers = 1.25. However, by using function here i get a different number 0.63.
I am trying to figure out where the mistake is, but i am stuck. Can someone explain me where my mistake is, and maybe give me some advice? As a beginner, i will accept any constructive remarks/criticism.
float conso(char posteVoulu, char poste[], int nbElem, int tableau[])
{
int i ;
float somme = 0.0;
for(i = 0; i < nbElem; i++)
{
if (poste[i] == posteVoulu)
{
somme += tableau[i];
}
}
return somme / nbElem;
}
void afficher(int age[], int nbCafe[], char poste[], int nbPers)
{
int i;
printf("Contenu des 3 tableaux:\n\n");
printf(" Indice Age #Cafe Poste\n");
for ( i = 0; i < nbPers; i++)
{
printf("%5d%8d %6d ", i, age[i], nbCafe[i]);
switch (poste[i])
{
case 'A' :
printf(" Analyste\n");
break;
case 'P' :
printf(" Programmeur\n");
break;
case 'O' :
printf(" Operateur\n");
break;
}
}
printf("\n");
}
int main()
{
char poste[] = {'A', 'P', 'O', 'P', 'A', 'O', 'P', 'P'};
int age[]= {25, 18, 23, 20, 49, 24, 56, 29},
nbCafe[] = {3, 1, 6, 1, 4, 1, 0, 3} ;
int nbPers = sizeof(age) / sizeof(int);
afficher(age, nbCafe, poste, nbPers);
printf("La consomation moyenne de cafe des programmeurs : %.2f\n",
conso('P', poste, nbPers, nbCafe));
printf("\n");
system("pause") ;
return 0;
}
Upvotes: 0
Views: 109
Reputation: 4767
In your new code, you are dividing the coffee consumed by programmers (5) by ALL people (8). In your original code, you first counted the number of programmers (4). Here's a fixed up version of conso
:
float conso(char posteVoulu, char poste[], int nbElem, int tableau[])
{
int i;
float somme = 0.0;
int nbPers = 0;
for(i = 0; i < nbElem; i++)
{
if (poste[i] == posteVoulu)
{
somme += tableau[i];
nbPers++;
}
}
if (nbPers == 0)
return 0;
return somme / nbPers;
}
Upvotes: 4