C++编写程序,找出一个5行5列的二维数组的靶点,即该位置上的元素在该行元素中最大
时间: 2024-03-09 17:49:26 浏览: 65
且在该列元素中最小。以下是C++程序的示例代码:
```c++
#include <iostream>
using namespace std;
int main() {
int matrix[5][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}};
int rowMax, colMin, targetRow, targetCol;
bool found = false;
for (int i = 0; i < 5; i++) {
rowMax = matrix[i][0];
for (int j = 1; j < 5; j++) {
if (matrix[i][j] > rowMax) {
rowMax = matrix[i][j];
}
}
for (int j = 0; j < 5; j++) {
colMin = matrix[0][j];
for (int k = 1; k < 5; k++) {
if (matrix[k][j] < colMin) {
colMin = matrix[k][j];
}
}
if (matrix[i][j] == rowMax && matrix[i][j] == colMin) {
targetRow = i;
targetCol = j;
found = true;
break;
}
}
if (found) {
break;
}
}
if (found) {
cout << "The target point is at (" << targetRow << "," << targetCol << ") and its value is " << matrix[targetRow][targetCol] << endl;
} else {
cout << "The target point is not found" << endl;
}
return 0;
}
```
在上述程序中,我们首先定义了一个5行5列的二维数组`matrix`,然后使用两个for循环分别找出每一行的最大值和每一列的最小值,同时在第二个for循环中判断当前元素是否为靶点。如果找到了靶点,我们就记录下它的行和列,并将`found`标记为`true`,然后跳出所有循环。最后,我们根据`found`的值来输出结果。
阅读全文