4 回答
TA贡献1817条经验 获得超6个赞
您将所有输入的数字存储在列表中并从那里计算:
def avg_pos(d):
if len(d) == 0: # avoid div by 0
return 0
return sum(d)/len(d)
data = []
while True:
try:
n = input("Number: ")
if n == "#":
break
n = int(n)
data.append(n)
except ValueError:
print("Not a number")
print( f"Min: {min(data)} Max: {max(data)} AvgP: {avg_pos([d for d in data if d>0])}" )
输出:
Number: 4
Number: 5
Number: 6
Number: -2
Number: -99
Number: 73
Number: #
Min: -99 Max: 73 AvgP: 22.0
TA贡献1850条经验 获得超11个赞
每次接受正数时求总和并计算每个数字。最后你可以确定平均值
maximum = None
minimum = None
sum_of_positive = 0
count_of_positive = 0
num = None
while True:
inp = input("PLease enter a number: ")
if inp == "#" :
break
try:
num=float(inp)
except:
print ("Error with this input")
continue
if maximum is None:
maximum = num
minimum = num
if num>maximum:
maximum=num
if num<minimum:
minimum=num
if num > 0:
sum_of_positive = sum_of_positive + num
count_of_positive = count_of_positive + 1
if count_of_positive > 0:
average_of_positive = sum_of_positive / count_of_positive
else:
average_of_positive = 0
print ("The Maximum is ", maximum)
print ("The Minimum is ", minimum)
print ("The Average of Positive Numbers is ", average_of_positive)
TA贡献1794条经验 获得超8个赞
使用max
、min
和 等库函数sum
。
例如max([1,2,3,5,11,8])
给你 11,min([1,2,3,5,11,8])
给你 1,sum([1,2,3,5,11,8])
给你 30。
假设您将数字读入名为 的列表numbers
,然后获取最大数字为max(numbers)
,最小数字为min(numbers)
,平均值为sum(numbers)/len(numbers)
。
请注意,如果您使用 python 2,那么您需要在除法之前转换为 float,如下所示float(sum(numbers))/len(numbers)
。
添加回答
举报