2.1.2 练习 for 循环求数组元素的最大值

C++自学精简教程 目录(必读)

求数组 [3 1 4 1 5 9 2 6]中的最大值9的过程

求数组的最大值,实际上是遍历数组,不断更新我们已经找到的最大值的过程

原始数组

用一个变量max来存已经找到的最大值,一开始把3当作最大值

找到一个新的最大值4

max值更新为4

遍历完数组所有元素,找到最大值9存储于max中

C++实现:

1 下标for循环实现

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    vector<int> arr{ 3,1,4,1,5,9,2,6 };
    
    int max = arr[0];
    for (int i = 1; i < arr.size(); ++i)
    {
        if (arr[i] > max)
        {
            //(1) your code 

        }
    }

    cout << "max=" << max;

    return 0;
}

调用max函数实现(仅作参考)

接下来的实现利用了 求两个数的最大值max 中的函数。

完整代码

#include<iostream>
#include<vector>
using namespace std;

int max(int a, int b)
{
    return a >= b ? a : b;
}

int main()
{
    vector<int> arr{ 3,1,4,1,5,9,2,6 };

    int result_max = arr[0];

    for (int i = 1; i < arr.size(); ++i)
    {
        result_max = max(result_max, arr[i]);
    }

    cout << "max=" << result_max;

    return 0;
}

使用函数max求数组的最大值

思考:如何求出数组的最小值?

如需答案和答疑:请私信。