这是找到最大的数字和他的行的好方法,但是我不知道如何找到最小的数字。我试图比较它像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);
}