c++求一维数组的最大值
时间: 2024-02-03 15:03:58 浏览: 41
你可以通过遍历数组,逐个比较元素大小,找到数组中的最大值。以下是一个示例的 C 代码:
```c
#include <stdio.h>
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[] = {1, 5, 3, 9, 2};
int size = sizeof(arr) / sizeof(arr[0]);
int max = findMax(arr, size);
printf("最大值为:%d\n", max);
return 0;
}
```
输出结果为:
```
最大值为:9
```
相关问题
指针求二维数组最大值
指针求二维数组最大值的方法如下:
1. 首先,定义一个指向二维数组的指针。
2. 使用两个嵌套的循环遍历整个二维数组,比较每个素的值与当前最大值。
3. 如果找到更大的值,更新最大值。
4. 最后返回最大值。
以下是一个示例代码:
```c++
int findMax(int *arr, int rows, int cols) {
int maxVal = *arr; // 初始化最大值为数组第一个元素的值
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (*(arr + i * cols + j) > maxVal) {
maxVal = *(arr + i * cols + j);
}
}
}
return maxVal;
}
```
C++ 求一维数组中最大、最小元素
可以使用循环遍历数组,利用一个变量记录最大值和最小值,每次循环比较更新即可。
示例代码:
```c
#include <stdio.h>
int main() {
int arr[] = {3, 5, 2, 9, 1, 7, 4, 8, 6};
int len = sizeof(arr) / sizeof(int);
int max = arr[0], min = arr[0];
for (int i = 1; i < len; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
printf("The maximum element is %d\n", max);
printf("The minimum element is %d\n", min);
return 0;
}
```
输出结果:
```
The maximum element is 9
The minimum element is 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![c](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)