gpt4 book ai didi

python - 计算列表中数字的平均值

转载 作者:太空宇宙 更新时间:2023-11-03 20:41:08 25 4
gpt4 key购买 nike

查找 5 个数字求数字的平均值

#import statistics
print("enter 5#s")
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = int(input())
num5 = int(input())
numbers = [num1, num2, num3, num4, num5]
numsum = sum(numbers)
print("sum is:", numsum)
#Above list is working
#fix below
def Average(numbers):
return sum(numbers) / len(numbers)
print("AVG = ", round(Average, 2))

错误回溯(最近一次调用最后一次):文件“main.py”,第 15 行print("AVG = ", round(平均值, 2))类型错误:类型函数不符合define_round_method

最佳答案

最后一行(调用print)

def Average(numbers):
return sum(numbers) / len (numbers)
print("AVG = ", round(Average, 2))

需要不缩进(移到左侧,在函数之外)并且需要使用数字作为其参数来调用该函数,如下所示:

def Average(numbers):
return sum(numbers) / len (numbers)
print("AVG = ", round(Average(numbers), 2))
<小时/>

您的代码可以简化和改进,也许像这样:

num_list = []
for i in range(5):
s = input('Enter the {}. number: '.format(i+1))
n = int(s)
num_list.append(n)

the_sum = sum(num_list)
print('Sum:', the_sum)

the_avg = round(the_sum / len(num_list), 2)
print('Avg:', the_avg)

示例运行:

Enter the 1. number: 7
Enter the 2. number: 5
Enter the 3. number: 4
Enter the 4. number: 4
Enter the 5. number: 4
Sum: 24
Avg: 4.8

关于python - 计算列表中数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com