计算n个数的最大值、最小值、平均值

问题是编写一个程序,要求用户输入一系列数字并输出,该系列中的最大数字,该系列中的最小数字以及所有正数的平均值。


我当前的代码计算最小值和最大值,但我不知道如何编写代码来计算平均值。


maximum = None

minimum = None

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


print ("The Maximum is ", maximum)

print ("The Minimum is ", minimum)


UYOU
浏览 155回答 4
4回答

慕的地6264312

您将所有输入的数字存储在列表中并从那里计算:def avg_pos(d):&nbsp; &nbsp; if len(d) == 0: # avoid div by 0&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; return sum(d)/len(d)data = []while True:&nbsp; &nbsp; try:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; n = input("Number: ")&nbsp; &nbsp; &nbsp; &nbsp; if n == "#":&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; n = int(n)&nbsp; &nbsp; &nbsp; &nbsp; data.append(n)&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print("Not a number")print( f"Min: {min(data)}&nbsp; Max: {max(data)}&nbsp; AvgP: {avg_pos([d for d in data if d>0])}" )输出:Number: 4Number: 5Number: 6Number: -2Number: -99Number: 73Number: #Min: -99&nbsp; Max: 73&nbsp; AvgP: 22.0&nbsp;

慕盖茨4494581

每次接受正数时求总和并计算每个数字。最后你可以确定平均值maximum = Noneminimum = Nonesum_of_positive = 0count_of_positive = 0num = Nonewhile True:&nbsp; &nbsp; inp = input("PLease enter a number: ")&nbsp; &nbsp; if inp == "#" :&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; num=float(inp)&nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; print ("Error with this input")&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; if maximum is None:&nbsp; &nbsp; &nbsp; &nbsp; maximum = num&nbsp; &nbsp; &nbsp; &nbsp; minimum = num&nbsp; &nbsp; if num>maximum:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; maximum=num&nbsp; &nbsp; if num<minimum:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; minimum=num&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if num > 0:&nbsp; &nbsp; &nbsp; &nbsp; sum_of_positive = sum_of_positive + num&nbsp; &nbsp; &nbsp; &nbsp; count_of_positive = count_of_positive + 1if count_of_positive > 0:&nbsp; &nbsp; average_of_positive = sum_of_positive / count_of_positiveelse:&nbsp; &nbsp; average_of_positive = 0print ("The Maximum is ", maximum)print ("The Minimum is ", minimum)print ("The Average of Positive Numbers is ", average_of_positive)

幕布斯7119047

使用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)。

沧海一幻觉

您需要添加一个counter变量来了解循环中有多少轮。而且你还需要一个total变量来总结所有num然后你只需要打印总计/计数器
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python