编写程序,由键盘输入20个整数,找出最大正整数,最小正整数,最大负整数,最小负整数
时间: 2024-10-22 12:14:33 浏览: 57
只能输入正整数的正则表达式及常用的正则表达式
5星 · 资源好评率100%
编写这样的程序,通常会在循环结构中获取用户输入,并通过变量存储找到的最大和最小正、负整数。以下是一个简单的Python示例:
```python
# 初始化最大正整数、最小正整数、最大负整数和最小负整数为None
max_positive = None
min_positive = None
max_negative = float('-inf')
min_negative = float('inf')
for _ in range(20):
num = int(input("请输入第{}个整数:".format(_ + 1)))
# 判断数是否为正整数
if num > 0 and (not max_positive or num > max_positive):
max_positive = num
# 同理判断其他情况
if num > 0 and min_positive is None or num < min_positive:
min_positive = num
elif num < 0 and (num > max_negative):
max_negative = num
elif num < 0 and (num < min_negative):
min_negative = num
# 输出结果
if max_positive is not None:
print("最大正整数是:", max_positive)
else:
print("未找到正整数")
if min_positive is not None:
print("最小正整数是:", min_positive)
else:
print("未找到正整数")
if max_negative != float('-inf'):
print("最大负整数是:", max_negative)
else:
print("未找到负整数")
if min_negative != float('inf'):
print("最小负整数是:", min_negative)
else:
print("未找到负整数")
```
阅读全文