用c++,找出给定一系列整数中的最小值。首先给出一个正整数n,之后是n个整数
时间: 2024-11-03 20:23:07 浏览: 114
在C++中,你可以使用`<algorithm>`库中的`min_element`函数来找到一系列整数中的最小值。下面是一个简单的示例:
```cpp
#include <iostream>
#include <vector>
#include <algorithm> // 包含 min_element 函数
int findMin(int n, std::vector<int>& numbers) {
// 检查数组是否为空
if (numbers.empty()) {
std::cerr << "Error: 数组为空." << std::endl;
return -1; // 或者抛出异常
}
// 使用 min_element 找到并返回最小值
int* minVal = &numbers[0]; // 算法需要一个迭代器
auto it = std::min_element(numbers.begin(), numbers.end());
return *it;
}
int main() {
int n;
std::cout << "请输入整数的数量(n): ";
std::cin >> n;
std::vector<int> numbers(n);
std::cout << "请输入" << n << "个整数: ";
for (int i = 0; i < n; ++i) {
std::cin >> numbers[i];
}
int minValue = findMin(n, numbers);
if (minValue != -1) {
std::cout << "最小值是: " << minValue << std::endl;
}
return 0;
}
```
这个程序首先读取输入的整数数量和数值,然后利用`findMin`函数寻找并返回最小值。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.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)
![](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)