鲷鱼烧很好吃 2023-05-11 19:13 采纳率: 50%
浏览 38
已结题

写出二维数组每列元素中的最大值

编写一个函数,该函数的功能是求M行N列二维数组每列元素中的最大值

  • 写回答

3条回答 默认 最新

  • 社区专家-Monster-XH 2023-05-11 20:35
    关注

    基于Monster 组和GPT的调写:

    c++

    #include <iostream>
    #include <climits>
    
    void findColumnMax(int arr[][N], int M, int N) {
        int maxVal;
        for (int j = 0; j < N; j++) {
            maxVal = INT_MIN; // 初始化为最小值
    
            // 找出每列的最大值
            for (int i = 0; i < M; i++) {
                if (arr[i][j] > maxVal) {
                    maxVal = arr[i][j];
                }
            }
    
            std::cout << "Column " << j + 1 << " max value: " << maxVal << std::endl;
        }
    }
    
    int main() {
        const int M = 3; // 行数
        const int N = 4; // 列数
        int arr[M][N] = {{1, 2, 3, 4},
                         {5, 6, 7, 8},
                         {9, 10, 11, 12}};
    
        findColumnMax(arr, M, N);
    
        return 0;
    }
    
    
    

    c

    #include <stdio.h>
    #include <limits.h>
    
    void findColumnMax(int arr[][N], int M, int N) {
        int maxVal;
        for (int j = 0; j < N; j++) {
            maxVal = INT_MIN; // 初始化为最小值
    
            // 找出每列的最大值
            for (int i = 0; i < M; i++) {
                if (arr[i][j] > maxVal) {
                    maxVal = arr[i][j];
                }
            }
    
            printf("Column %d max value: %d\n", j + 1, maxVal);
        }
    }
    
    int main() {
        const int M = 3; // 行数
        const int N = 4; // 列数
        int arr[M][N] = {{1, 2, 3, 4},
                         {5, 6, 7, 8},
                         {9, 10, 11, 12}};
    
        findColumnMax(arr, M, N);
    
        return 0;
    }
    
    
    

    这两个示例代码中,findColumnMax函数用于遍历二维数组,找出每列的最大值,并打印出来。在函数中,我们使用INT_MIN(C++版本)或INT_MIN(C语言版本)来初始化最大值,然后逐列遍历,比较每个元素与当前最大值的大小,并更新最大值。最后,打印出每列的最大值。

    本回答被专家选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 5月22日
  • 专家已采纳回答 5月14日
  • 创建了问题 5月11日