帮我写一个代码,用c++,3.编写自定义函数找出二维数组(3*4)中元素的最大值与最小值,并返回其最大值与最小值,并在main函数中测试结果。要求: (1)数组在main函数中使用随机函数获得赋值; (2)自定义函数返回类型为void; (3)输出结果在main函数中实现。
时间: 2024-05-12 12:20:31 浏览: 72
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void findMaxMin(int arr[][4], int rows, int cols, int *max, int *min);
int main() {
int arr[3][4];
int max, min;
srand(time(NULL));
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 4; j++) {
arr[i][j] = rand() % 100;
printf("%d ", arr[i][j]);
}
printf("\n");
}
findMaxMin(arr, 3, 4, &max, &min);
printf("The maximum value is %d, and the minimum value is %d.\n", max, min);
return 0;
}
void findMaxMin(int arr[][4], int rows, int cols, int *max, int *min) {
*max = *min = arr[0][0];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(arr[i][j] > *max) {
*max = arr[i][j];
}
if(arr[i][j] < *min) {
*min = arr[i][j];
}
}
}
}
```
输出:
```
70 96 58 64
62 53 76 49
98 79 56 71
The maximum value is 98, and the minimum value is 49.
```
阅读全文