矩阵最大值

题目截图:

思路:

  对矩阵的每一行求出最大值以及和,并记录最大值下标,最后将最大值所在位置换成本行元素的和即可。

 

代码如下:

 1 /*
 2     矩阵最大值 
 3 */
 4 
 5 #include <stdio.h>
 6 #include <string.h>
 7 #include <math.h>
 8 #include <stdlib.h>
 9 #include <time.h>
10 #include <stdbool.h>
11 
12 #define maxm 101
13 #define maxn 101
14 int rec[maxm][maxn];                            // 用来存储矩阵元素 
15 
16 int main() {
17     int m, n, i, j; 
18     while(scanf("%d %d", &m, &n) != EOF) {        // 输入矩阵行数、列数 
19         for(i=0; i<m; ++i) {
20             for(j=0; j<n; ++j) {
21                 scanf("%d", &rec[i][j]);        // 输入矩阵 
22             }
23         }
24         for(i=0; i<m; ++i) {
25             int k=0, sum=rec[i][0];                // k记录最大值下标,sum记录行元素的和 
26             for(j=1; j<n; ++j) {
27                 sum += rec[i][j];
28                 if(rec[i][j] > rec[i][k]) {
29                     k = j;
30                 }
31             }
32             rec[i][k] = sum;                    // 将最大值所在位置换成行元素的和 
33         }
34         for(i=0; i<m; ++i) {                    // 按格式输出 
35             for(j=0; j<n; ++j) {
36                 printf("%d", rec[i][j]);
37                 if(j != n-1) {
38                     printf(" ");
39                 }
40             }
41             printf("
");
42         }
43     }
44 
45     return 0;
46 }
原文地址:https://www.cnblogs.com/coderJiebao/p/HustTest15.html