[英]C: Finding maximum average of a 2 dimensional array
我想要的输出是平均分数的最大值,例如,哪一行是:
9.33(avg) 4(row)
9.33(avg) 5(row)
但是我的输出是这样的:
9.33 0
9.33 4
9.33 5
谁能为我解释为什么我的输出是这样以及如何解决它?
#include <stdio.h>
#include <string.h>
#define D 3
#define C 10
int main()
{
float num[D][C] =
{
{5.0, 8.0, 7.5, 4.5, 9.0, 9.0, 6.5, 3.0, 4.5, 8.5},
{6.0, 8.5, 7.0, 5.0, 9.5, 9.5, 6.5, 2.5, 5.0, 7.5},
{5.5, 8.0, 6.5, 7.5, 9.5, 9.5, 6.5, 4.0, 5.5, 9.5},
};
int i, j,e,l;
float d,a,b,c,max,k,x,y,z,o;
float p1,p2,p3,p4;
k=0;
max=0;
for(j=0; j<10; j++)
{
a=num[0][j];
b=num[1][j];
c=num[2][j];
d=(a+b+c)/3;
if(max<=d )
{
for(l=0; l<10; l++)
{
x=num[0][l];
y=num[1][l];
z=num[2][l];
o=(x+y+z)/3;
if(max<o)
{
max=o;
}
}
printf("%0.2f %d\n",max,j);
}
}
}
评论中已经给出了一些建议。 定义数组的大小并重用循环中的定义可避免溢出。 首先,计算平均值并记住最大值。 那么您可以轻松地将它们与最大值和存储的平均值进行比较,以输出它们。
#define D 3
#define C 10
float num[D][C] = {
{5.0, 8.0, 7.5, 4.5, 9.0, 9.0, 6.5, 3.0, 4.5, 8.5},
{6.0, 8.5, 7.0, 5.0, 9.5, 9.5, 6.5, 2.5, 5.0, 7.5},
{5.5, 8.0, 6.5, 7.5, 9.5, 9.5, 6.5, 4.0, 5.5, 9.5},
};
float avg[C]; /*will hold all the average values*/
float max = 0; /*will hold the maximum vlaue*/
int i, j;
for (i = 0; i < C; i++) {
float sum = 0;
/*sum columns*/
for (j = 0; j < D; j++) {
sum += num[j][i];
}
/*memorize calculated avg*/
avg[i] = sum / D;
/*check if maximum*/
if (max < avg[i])
max = avg[i];
}
/*output index and average*/
for (i = 0; i < C; i++)
if (avg[i] == max)
printf("%0.2f %d\n",max,i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.