python 从键盘输入若干个整数,当输入"-1""时输入结束,请统计最大值、最小值和平均数
上面题目代码如下:
第一种方法列表方法求:
a=[]b = int(input())while True: if b == -1: break a.append(b) b=int(input()) if b==-1: breakif 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这种情况,做了如下处理:
来源地址:https://blog.csdn.net/Deng872347348/article/details/127182106