如何用c++计算并获取数组中的最大值?
时间: 2025-01-26 16:06:16 浏览: 30
在C++中,可以通过遍历数组来计算并获取数组中的最大值。以下是一个简单的示例代码,展示了如何实现这一功能:
```cpp
#include <iostream>
#include <vector>
int findMax(const std::vector<int>& arr) {
if (arr.empty()) {
throw std::invalid_argument("Array is empty");
}
int maxValue = arr[0];
for (size_t i = 1; i < arr.size(); ++i) {
if (arr[i] > maxValue) {
maxValue = arr[i];
}
}
return maxValue;
}
int main() {
std::vector<int> numbers = {3, 5, 7, 2, 8, 1, 9};
try {
int maxNumber = findMax(numbers);
std::cout << "The maximum number in the array is: " << maxNumber << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
```
在这个示例中,`findMax`函数接受一个整数向量作为参数,并返回其中的最大值。函数首先检查数组是否为空,如果为空则抛出一个异常。然后,函数通过遍历数组来找到最大值并返回。
`main`函数中定义了一个整数向量,并调用`findMax`函数来获取其中的最大值并输出。
阅读全文
相关推荐


















