我知道如何找到最大的数字,但不知道如何打印该行? ................................................... ................................................... ..........
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
int i,j,n, max_i, max_j;
printf("Input size of a matrix:");
scanf("%d", &n);
int mat[n][n];
printf("Input numbers in matrix:");
for (i=0;i<n;i++){
for (j=0;j<n;j++){
scanf("%d", &mat[i][j]);
}
}
max_i=0;
max_j=0;
for (i=0;i<n;i++){
for (j=0;j<n;j++){
if(mat[max_i][max_j]>mat[i][j]){
mat[i][j]=mat[max_i][max_j];
}
}
}
printf("Largest number is %d, print of his whole row is %d", mat[max_i][max_j], mat[i][0] ); // I think here is a problem, but who knows
return 0;
}
答案 0 :(得分:1)
您所做的几乎是正确的,也就是说,您实际上是在寻找最大数字所在的索引(而不只是获取最大数字的值)。
更新max-indices只是一个错误,因为...
if(mat[max_i][max_j]>mat[i][j]){
mat[i][j]=mat[max_i][max_j]; // alters the contents of the matrix
}
更改矩阵的内容,而不是更新搜索的索引。
写
if(mat[max_i][max_j] < mat[i][j]){
max_i = i;
max_j = j;
}
,最后应该有最大值所在的索引:
printf("maximum value is %d and is located at %d/%d\",mat[max_i][max_j],max_i,max_j);
答案 1 :(得分:1)
如果google翻译正确,并且我理解您想要什么-因此您需要一张一张地打印它,或者在循环之前收集它:
printf("Najveci broj je %d, a ispis cijelog retka je ", mat[max_i][max_j]);
for(j = 0; j < n; j++) {
printf("%d ", mat[max_i][j]);
}
答案 2 :(得分:0)
创建一个变量以存储最大数目和该数目的行。
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
int i,j,n, max_number, max_number_row;
printf("Ucitajte velicinu matrice:");
scanf("%d", &n);
int mat[n][n];
printf("Ucitajte brojeve u matricu:");
for (i=0;i<n;i++){
for (j=0;j<n;j++){
scanf("%d", &mat[i][j]);
}
}
max_number = mat[0][0];
for (i=0;i<n;i++){
for (j=0;j<n;j++){
if(mat[i][j] > max_number){
max_number = mat[i][j];
max_number_row = i;
}
}
}
printf("Najveci broj je %d, a ispis cijelog retka je %d", max_number, max_number_row );
return 0;
}
编辑1:
就像另一个答案中提到的myxaxa一样,如果要打印行的每个数字,都需要遍历max_number_row。
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
int i,j,n, max_number, max_number_row;
printf("Ucitajte velicinu matrice:");
scanf("%d", &n);
int mat[n][n];
printf("Ucitajte brojeve u matricu:");
for (i=0;i<n;i++){
for (j=0;j<n;j++){
scanf("%d", &mat[i][j]);
}
}
max_number = mat[0][0];
for (i=0;i<n;i++){
for (j=0;j<n;j++){
if(mat[i][j] > max_number){
max_number = mat[i][j];
max_number_row = i;
}
}
}
printf("Najveci broj je %d, a ispis cijelog retka je ", max_number);
for(j = 0; j < n; j++) {
printf("%d ", mat[max_number_row][j]);
}
return 0;
}