简体   繁体   中英

C: Finding maximum average of a 2 dimensional array

The output that I want is the max of an average score and which row is that for example:

9.33(avg) 4(row)

9.33(avg) 5(row)

But my output is this:

9.33 0

9.33 4

9.33 5

Can anyone explain for me why my output is like this and how I could fix it?

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

some suggestions were given in the comments already. define the size of the arrays and reuse the defines in the loops do avoid overflows. at first calculate the averages and memorize the maximum value. then you can easily output them comparing your maximum value to the memorized avg values.

#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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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