gpt4 book ai didi

c - 关于在 C 中使用 "functions"

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:38 24 4
gpt4 key购买 nike

我是编程的初学者,几天来我一直被以下问题所困扰。

我正在重写 this我创建的一段代码,仅使用“函数”。请注意,在执行原件时,我们有程序员的平均咖啡消耗量 = 1.25。但是,通过使用函数 here我得到一个不同的数字 0.63

我试图找出错误所在,但我被卡住了。 谁能解释一下我的错误在哪里,也许能给我一些建议?作为初学者,我会接受任何建设性的评论/批评。

代码:

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

最佳答案

在您的新代码中,您将程序员消耗的咖啡 (5) 除以所有人 (8)。在您的原始代码中,您首先统计了程序员的数量(4)。这是 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;
}

关于c - 关于在 C 中使用 "functions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27162738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com