题目描述 任意输入n个整数,把它们的最大值,最小值求出来. 输入 输入只有一行,包括一个整数n(1<=n<=20),后面跟着n个数. 每个数的范围在0到32767之间。 输出 输出只有一行,包括2个整数。
时间: 2024-02-13 11:02:23 浏览: 111
好的,这道题可以使用 Python 或者 C++ 来实现。以下是 Python 实现的代码:
```python
n = int(input()) # 输入 n
nums = list(map(int, input().split())) # 输入 n 个数,转化为列表
max_num = max(nums) # 使用 max 函数求最大值
min_num = min(nums) # 使用 min 函数求最小值
print(max_num, min_num) # 输出最大值和最小值
```
以下是 C++ 实现的代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm> // 包含 max 和 min 函数
using namespace std;
int main() {
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
int max_num = *max_element(nums.begin(), nums.end()); // 使用 max_element 函数求最大值
int min_num = *min_element(nums.begin(), nums.end()); // 使用 min_element 函数求最小值
cout << max_num << " " << min_num << endl; // 输出最大值和最小值
return 0;
}
```
这里使用了 Python 内置的 `max()` 和 `min()` 函数,以及 C++ 中的 `max_element()` 和 `min_element()` 函数,简化了代码的编写。注意,在 C++ 中使用 `max_element()` 和 `min_element()` 函数时,需要使用解引用运算符 `*` 取出指向最大(小)值的迭代器所指向的元素。
阅读全文
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.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)