簡體   English   中英

如何找到最小的行數(二維數組)C編程

[英]How to find the smallest sum of rows(2D array) C programming

這是找到最大的數字和他的行的好方法,但是我不知道如何找到最小的和。 我試圖比較它像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;
}

我認為一些人提供的意見已經為您指明了方向。 我只是總結了您需要檢查的所有更改。

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

我想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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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