编写一个函数,该函数的功能是求M行N列二维数组每列元素中的最大值
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语言版本)来初始化最大值,然后逐列遍历,比较每个元素与当前最大值的大小,并更新最大值。最后,打印出每列的最大值。
#include <stdio.h>
#define MAXM 10
#define MAXN 10
//编写一个函数,该函数的功能是求M行N列二维数组每列元素中的最大值
//Enter m,n:4 4
//Enter m*n num:
//1 3 5 6
//10 3 4 15
//20 30 40 1
//80 20 30 10
//6 15 40 80
int main()
{
int i,j,n,m,max;
int a[MAXN][MAXN];
printf("Enter m,n:");
scanf("%d%d",&m,&n);
printf("Enter m*n num:\n");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d",&a[i][j]);
}
}
max=0;
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(max<a[j][i]){
max=a[i][j];
}
}
printf("%d ",max);
max=0;
}
}
为了熟悉二维数组的指针表示,部分代码给出了数组表示和指针表示
#include<stdio.h>
#include<string.h>
#define M 3
#define N 4
/**
编写:fun()
功能:将M行N列的二维数组中的字符数据,按列的顺序依次放到一个字符串中
例如:
二维数组中的数据为:
W W W W
S S S S
H H H H
则字符串中的内容是:WSHWSHWSH
**/
// 0 1 2 3
// 0 W W W W
// 1 S S S S
// 2 H H H H
char *fun(char s[M][N], char *res) {
int t = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
res[t++] = s[j][i];
// res[t++] = *(*(a*i)+i); // 指针表示
}
}
res[t] = '\0';
return res;
}
int main(int argc, char const *argv[]) {
char a[M][N] = {'M', 'M', 'M', 'M', 'S', 'S', 'S', 'S', 'H', 'H', 'H', 'H'};
int size_res = M*N;
char res[size_res];
printf("二维数组中元素:\n");
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
printf("%c\t", a[i][j]);
// printf("%c\t", *(*(a*i)+j)); // 指针表示
}
printf("\n");
}
printf("按列的顺序依次:\n%s\n", fun(a, res));
}
示例结果:
$ gcc ex002.c -o demo
$ ./demo
二维数组中元素:
M M M M
S S S S
H H H H
按列的顺序依次:
MSHMSHMSHMSH