簡體   English   中英

C:求二維數組的最大平均值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM