python 从键盘输入若干个整数,当输入“-1““时输入结束,请统计最大值、最小值和平均数
原创
©著作权归作者所有:来自51CTO博客作者wx636b527159a1e的原创作品,请联系作者获取转载授权,否则将追究法律责任
python 从键盘输入若干个整数,当输入"-1""时输入结束,请统计最大值、最小值和平均数
上面题目代码如下:
第一种方法列表方法求:
a=[]
b = int(input())
while True:
if b == -1:
break
a.append(b)
b=int(input())
if b==-1:
break
if b==-1:
print('Count is 0')
print(f'Max number is 0')
print(f'Min number is 0')
print('The average number is 0')
else:
print('Count is ' + str(len(a)))
print(f'Max number is{max(a)}')
print(f'Min number is{min(a)}')
print('The average number is ' + str(sum(a) / len(a)))
第二种方法,冒泡排序算法求得
arr=[]
while True:
a = int(input())
if a==-1:
break
# 遍历所有数组元素
arr.append(a)
print(type(arr))
for i in range(len(arr)):
# Last i elements are already in place
for j in range(0, len(arr) - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if a==-1:
print('Count is 0' )
print(f'Max number is 0')
print(f'Min number is 0')
print('The average number is 0' )
else:
print('Count is ' + str(len(arr)))
print(f'Max number is{arr[0]}')
print(f'Min number is{arr[-1]}')
print('The average number is ' + str(sum(arr) / len(arr)))
代码中,考虑到-1这种情况,做了如下处理: