从键盘输入任意数目的整数n(n>=3),使用这些数据创建列表,输出其中的最大值及其相邻元素。
时间: 2023-04-30 12:01:49 浏览: 178
可以按照以下步骤来实现:
1. 从键盘输入整数n,保证n>=3。
2. 创建一个空列表,用于存储输入的整数。
3. 使用for循环,从键盘输入n个整数,并将它们添加到列表中。
4. 使用for循环遍历列表,找到最大值及其相邻元素。
5. 输出最大值及其相邻元素。
代码示例:
n = int(input("请输入整数个数:"))
assert n >= 3, "输入的整数个数必须大于等于3"
nums = []
for i in range(n):
num = int(input("请输入第{}个整数:".format(i+1)))
nums.append(num)
max_num = nums[0]
max_index = 0
for i in range(1, n):
if nums[i] > max_num:
max_num = nums[i]
max_index = i
if max_index == 0:
print("最大值为{},相邻元素为{}和{}".format(max_num, nums[max_index+1], nums[max_index+2]))
elif max_index == n-1:
print("最大值为{},相邻元素为{}和{}".format(max_num, nums[max_index-2], nums[max_index-1]))
else:
print("最大值为{},相邻元素为{}和{}".format(max_num, nums[max_index-1], nums[max_index+1]))
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)