c++提取出数组中最大值
时间: 2023-11-03 14:06:13 浏览: 51
可以通过循环遍历数组,依次比较每个元素的大小,得出最大值。
以下是C语言示例代码:
```
#include <stdio.h>
int main() {
int arr[] = {5, 2, 8, 3, 9, 4};
int len = sizeof(arr) / sizeof(arr[0]); // 数组长度
int max = arr[0]; // 假设第一个元素为最大值
// 遍历数组,找出最大值
for (int i = 1; i < len; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("数组中最大值为:%d", max);
return 0;
}
```
相关问题
c++找出数组中的最大值
以下是使用C语言编写的找出数组中最大值的示例代码:
```c
#include <stdio.h>
// 定义数组大小
#define SIZE 5
int main()
{
int arr[SIZE] = {5, 8, 3, 9, 2}; // 初始化数组
int max = arr[0]; // 假设第一个元素为最大值
// 遍历数组,找到最大值
for (int i = 1; i < SIZE; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("最大值为:%d\n", max);
return 0;
}
```
输出结果为:最大值为9。
C++获取数组中最大值
要获取数组中的最大值,你可以使用循环遍历数组,并通过比较逐个找出最大值。以下是一个示例代码:
```c++
#include <iostream>
int main() {
int arr[] = {5, 2, 9, 1, 7};
int size = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
std::cout << "最大值为: " << max << std::endl;
return 0;
}
```
在上述代码中,我们首先定义了一个整型数组 `arr`,然后通过计算数组的大小来确定循环的终止条件。接着,我们初始化 `max` 变量为数组的第一个元素,并使用循环遍历数组中的元素。在每一次循环中,我们通过比较当前元素和 `max` 的值来更新 `max`,以确保它一直存储着当前找到的最大值。最后,我们输出 `max` 的值,即为数组中的最大值。
请注意,上述代码中假设数组至少包含一个元素。如果数组为空,你可能需要在代码中进行额外的判断或处理。