利用指针求矩阵的最大值
时间: 2023-11-04 12:01:14 浏览: 77
以下是一个简单的 C++ 代码示例,用于利用指针求矩阵的最大值:
```cpp
#include <iostream>
using namespace std;
int main() {
int rows, cols;
cout << "Enter the number of rows and columns: ";
cin >> rows >> cols;
// Allocate memory for the matrix
int **matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// Input matrix elements
cout << "Enter the matrix elements:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
// Find the maximum element
int max = matrix[0][0];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
}
cout << "The maximum element in the matrix is: " << max << endl;
// Free memory
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
return 0;
}
```
在此示例中,我们首先从用户输入中获取矩阵的行数和列数。然后,我们动态分配一个二维整数数组作为矩阵,并从用户输入中读取矩阵元素。接下来,我们使用两个嵌套的循环遍历整个矩阵,并找到最大元素。最后,我们输出最大元素并释放动态分配的内存。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)