用c语言编写自定义函数GetMax,返回二维数组a(m行n列)的最大元素值的代码
时间: 2024-02-03 12:13:27 浏览: 91
以下是使用C语言编写的自定义函数GetMax,返回二维数组a(m行n列)的最大元素值的代码:
```c
#include <stdio.h>
int GetMax(int m, int n, int a[][n]) {
int max = a[0][0];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] > max) {
max = a[i][j];
}
}
}
return max;
}
int main() {
int a[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int max = GetMax(3, 4, a);
printf("The maximum element in the array is %d\n", max);
return 0;
}
```
在上述代码中,我们首先定义了一个自定义函数GetMax,该函数接受三个参数:m表示二维数组的行数,n表示二维数组的列数,a表示二维数组的名称。我们使用两个for循环遍历整个二维数组,并使用if语句比较每个元素与当前的最大值。如果当前元素大于最大值,则将最大值更新为当前元素。最后,我们返回最大值。
在主函数中,我们定义了一个3x4的二维数组,并调用GetMax函数来获取数组的最大元素值。我们使用printf函数输出结果。
阅读全文