如何查找具有最大值的多维数组的索引

时间:2017-05-25 08:15:24

标签: c arrays

我有这个代码示例来查找最大使用天数,就像魅力一样。但我需要得到哪个array index具有最大值。我尝试了很多方法,但无法提出解决方案。这就是我的尝试:

#include<stdio.h>
int main(){
    float maximumDayUsage=0,minimumDayDayUsage=0;
    int whichDayHasMaximumUsage;
    float usage[7][5]={ {1.2, 2.1, 0.8, 0.0, 4.1},
                        {1.0, 1.3, 4.0, 1.5, 7.8},
                        {3.2, 1.0, 1.3, 4.0, 9.5},
                        {1.5, 3.2, 2.3, 0.4, 7.4}, 
                        {1.2, 2.1, 0.8, 0.0, 4.1},
                        {2.6, 2.1, 1.7, 7.0, 13.4},
                        {1.2, 2.1, 0.8, 0.0, 4.1} };
    for(int i=0;i<7;i++){
        for(int j=0;j<5;j++){
            if(usage[i][j]>maximumDayUsage){
                maximumDayUsage=usage[i][j];
                whichDayHasMaximumUsage++; 
            }else{

            }
        }
    }
    printf("Usage: %.2f\n",maximumDayUsage);
    printf("Which Day: %d",whichDayHasMaximumUsage);
    return 0;
}

1 个答案:

答案 0 :(得分:4)

在迭代数组时,只需保存最长使用日的ij索引:

int max_i = 0;
int max_j = 0;
float maximumDayUsage = 0;
for(int i=0;i<7;i++){
    for(int j=0;j<5;j++){
        if(usage[i][j] > maximumDayUsage) {
            maximumDayUsage = usage[i][j];
            max_i = i;
            max_j = j;
        }
    }
}