输入一个3×6的二维整数数组,输出其中最大值、最小值及其所在的行列下标。(用指针完成)
时间: 2024-02-03 22:12:54 浏览: 84
下面是C++的示例代码:
```cpp
#include <iostream>
using namespace std;
void findMinMax(int (*arr)[6], int row, int col, int* maxVal, int* minVal, int* maxRow, int* maxCol, int* minRow, int* minCol) {
*maxVal = **arr;
*minVal = **arr;
*maxRow = 0;
*maxCol = 0;
*minRow = 0;
*minCol = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (*(*(arr + i) + j) > *maxVal) {
*maxVal = *(*(arr + i) + j);
*maxRow = i;
*maxCol = j;
}
if (*(*(arr + i) + j) < *minVal) {
*minVal = *(*(arr + i) + j);
*minRow = i;
*minCol = j;
}
}
}
}
int main() {
int arr[3][6] = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}};
int maxVal, minVal, maxRow, maxCol, minRow, minCol;
findMinMax(arr, 3, 6, &maxVal, &minVal, &maxRow, &maxCol, &minRow, &minCol);
cout << "Max value: " << maxVal << ", row: " << maxRow << ", col: " << maxCol << endl;
cout << "Min value: " << minVal << ", row: " << minRow << ", col: " << minCol << endl;
return 0;
}
```
输出结果为:
```
Max value: 18, row: 2, col: 5
Min value: 1, row: 0, col: 0
```
在函数`findMinMax`中,我们使用了指针来接收最大值、最小值以及它们所在的行列下标。在计算时,我们使用了双重循环遍历整个二维数组,并不断更新最大值、最小值和它们所在的行列下标。注意,在使用指针时,需要使用`*`和`&`运算符来获取指针指向的值和地址。
阅读全文