首页 > 试题广场 >

给定一个二维数组,输出其最大值和最小值及其所在的行列位置。

[问答题]

给定一个二维数组,输出其最大值和最小值及其所在的行列位置。

#include <stdio.h>

#define MAX_ROW 5
#define MAX_COL 6

struct array_info {
  int ai_value;
  int ai_row;
  int ai_col;
};

int array[MAX_ROW][MAX_COL] = {
	{ 1, 2, 3, 4, 5, 6 },
	{ 2, 3, 4, 5, 6, 7 },
	{ -3, 4, 5, 6, 7, 8 },
	{ 4, 5, 6, 7, 8, 9 },
	{ 5, 6, 7, 8, 9, 0 }
};

int main(void)
{
    struct array_info max = { 0, 0, 0 };//0 is max for this code
    struct array_info min = { 0, 0, 0 };//0 is min for this code
    int row = 0;
    int column = 0;
    for (row = 0; row < MAX_ROW; row++)
    {
        for (column = 0; column < MAX_COL; column++)
        {
            if (array[row][column] > max.ai_value)
            {
                max.ai_value = array[row][column];
                max.ai_row = row;
                max.ai_col = column;
            }
            if (array[row][column] < min.ai_value)
            {
                min.ai_value = array[row][column];
                min.ai_row = row;
                min.ai_col = column;
            }
        }
    }
    printf("[max]value:%d, row:%d, col:%d\n", max.ai_value, max.ai_row, max.ai_col);
    printf("[min]value:%d, row:%d, col:%d\n", min.ai_value, min.ai_row, min.ai_col);
    return 0;
}

发表于 2021-04-27 19:06:29 回复(0)
#include"stdio.h"
int main()
{
    int a[2][3];
    int i,j,max,min,m=0,n=0,s=0,k=0;
    printf("please input:\n");
    for(i=0;i<2;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    max=a[0][0];
    min=a[0][0];
    for(i=0;i<2;i++)
    {
        for(j=0;j<3;j++)
        {
            if(a[i][j]>max)
            {
                max=a[i][j];
                m=i;
                n=j;
            }
            if(a[i][j]<min)
            {
                min=a[i][j];
                s=i;
                k=j;
            }
        }
        
    }
    printf("最大值为%d,其所在行标为%d,列标为%d\n",max,m,n);
    printf("最小值为%d,其所在行标为%d,列标为%d\n",min,s,k);
    return 0;
}
    


发表于 2021-01-29 15:36:05 回复(0)