用c++实现输入一个n×m的整数矩阵(n<=10,m<=10),然后输出其中的最大值、最小值,并输出这两个值的下标。
时间: 2024-10-26 14:17:34 浏览: 39
在C++中,你可以通过动态数组来存储矩阵,并使用两个变量分别记录最大值和最小值及其对应的索引。以下是实现这个功能的一种简单步骤:
```cpp
#include <iostream>
#include <vector>
int main() {
int n, m;
std::cout << "请输入矩阵的行数(n): ";
std::cin >> n;
std::cout << "请输入矩阵的列数(m): ";
std::cin >> m;
// 创建动态数组来表示矩阵
std::vector<std::vector<int>> matrix(n, std::vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
std::cout << "请输入第 " << (i+1) << " 行第 " << (j+1) << " 列的元素: ";
cin >> matrix[i][j];
}
}
int max_value = matrix[0][0], min_value = matrix[0][0];
int max_index = {0, 0}, min_index = {0, 0};
// 遍历矩阵寻找最大值和最小值
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] > max_value) {
max_value = matrix[i][j];
max_index = {i, j};
} else if (matrix[i][j] < min_value) {
min_value = matrix[i][j];
min_index = {i, j};
}
}
}
std::cout << "最大值(" << max_value << ")位于下标(" << max_index.first << ", " << max_index.second << ")." << std::endl;
std::cout << "最小值(" << min_value << ")位于下标(" << min_index.first << ", " << min_index.second << ")." << std::endl;
return 0;
}
```
阅读全文