简体   繁体   English

查找某个数组的平均值

[英]Finding average of a certain array

im trying to find the average coffee drank by the programmers. 我试图找到程序员平均喝的咖啡。 I can find and display the average but it just seems wrong, the way it is displayed. 我可以找到并显示平均值,但它的显示方式似乎只是错误的。 I just can't manage to extract the last line which displays the average. 我只是无法提取显示平均值的最后一行。

char poste[]={'A','P','A','P','A','O','P','P','O'};
int nbCafe[]={3,5,2,1,7,1,0,3,2};
int progonly=0;
float progmoyenne=0;

for(i=0;i<9;i++){
   if (poste[i]=='P'){
       progonly+=nbCafe[i];
       progmoyenne=progonly/4.0;}
printf("%f\n",progmoyenne);}

The execution gives this.(the last line is the average coffee drank): 执行给出此信息(最后一行是平均咖啡饮用量):

0.000000
0.000000
0.000000
0.000000
0.000000
0.250000
0.250000
1.000000
2.250000

If you just want to display the average, then just print the average. 如果只想显示平均值,则只打印平均值。 Move the printf outside the for loop. 将printf移动到for循环之外。

for(i=0;i<9;i++)
{
   if (poste[i]=='P')
   {
       progonly+=nbCafe[i];
       progmoyenne=progonly/4.0;
   }
}
printf("%f\n",progmoyenne);

put printf outside the for loop. printf放在for循环之外。 Also do declare i using int i; 还要使用int i;声明int i;

Try this one: 试试这个:

for(cnt=i=0;i<9;i++){
    if (poste[i]=='P'){
        progonly+=nbCafe[i];
        progmoyenne=progonly/(float)++cnt;
        printf("%f\n",progmoyenne);
    }
}

Output: 输出:

$ ./a.out 
5.000000
3.000000
2.000000
2.250000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM