求数组 [3 1 4 1 5 9 2 6]中的最大值9的过程
求数组的最大值,实际上是遍历数组,不断更新我们已经找到的最大值的过程





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;
}

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