如何找到最小的行数(二维数组)C编程

时间:2018-12-19 13:58:43

标签: c arrays

这是一个很好的方法,可以找到最大的数字和他的行,但是我不知道如何找到最小的数字。我试图比较它像mat [i] [j] <行的总和,但它不起作用。如果您能帮我一点忙

 #include <stdio.h>
#include <stdlib.h>

int main()

{
    int i, j,n, sum_row, min_row;

printf("Enter the size of an array: ");
scanf("%d", &n);
int mat[n][n];

printf("\nEnter numbers in array:");
for(i=0;i<n; i++){
    for (j=0;j<n;j++){
        scanf("%d", &mat[i][j]);
    }
}



min_row=mat[0][0];
for(i=0;i<n;i++){
        sum_row=0;
    for (j=0;j<n;j++){
            sum_row +=mat[i][j];


       if(mat[i][j]<sum_row)
            sum row=mat[i][j];
           /*  min_row=i; */

    }
}
printf("The smallest sum in rows is: %d, and row looks like", sum_row);


/*for(j=0;j<n;j++){
    printf(" %3d", min_row);
}*/





    return 0;
}

2 个答案:

答案 0 :(得分:0)

我认为一些人提供的意见已经为您指明了方向。我只是总结了您需要检查的所有更改。

#include <stdio.h>
#include <stdlib.h>

int main()

{
    int i, j,n, sum_row, min_row;

    printf("Enter the size of an array: ");
    scanf("%d", &n);
    int mat[n][n];

    printf("\nEnter numbers in array:");
    for(i=0;i<n; i++){
        for (j=0;j<n;j++){
            scanf("%d", &mat[i][j]);
        }
    }

    min_row = - 1;        // row index
    int row_min = 1<<31; // some large number, here I assume int is 32 bit on your machine.  this var saves the min value of row sum

    for(i=0;i<n;i++){
        sum_row = 0;

        for (j=0;j<n;j++){
            sum_row += mat[i][j];


            if(sum_row < row_min) {
                row_min = sum_row;
                min_row = i;
            }

        }
    }

    printf("The smallest sum in rows is: %d, and row looks like %d", row_min, min_row);
}

答案 1 :(得分:0)

我想n> = 1

int min_row =0;
int i, j;

// min_row is first the sum for first row
for (j=0;j<n;j++)
  min_row +=mat[0][j];

// look at other rows
for (i=1; i<n; i++) {
  // compute current row sum
  int sum_row = 0;

  for (j=0;j<n;j++)
    sum_row +=mat[i][j];

  // look at who is the smallest
  if(sum_row < min_row)
    min_row = sum_row;
}

printf("The smallest sum in rows is: %d", min_row);