用while循环求平均值

2024-05-29 02:45:33 发布

您现在位置:Python中文网/ 问答频道 /正文

窃听员七天来每天收集虫子。用Python编写一个程序,该程序保持七天内收集的bug数量的平均值。程序应该询问每天收集的bug数量,当循环结束时,程序应该显示每周收集的bug的平均数量。在

我试着运行我写的代码,但是它不能得到用户输入的所有数字的平均值。它只需要输入的第一个数字除以7。有人能告诉我我做错了什么吗?在

i = 1

while i < 8:

    bugs = int(input('enter the amount of bugs collected today:'))

    average = bugs / 7

    i+=1

print('average amount of bugs collected in a week is:', average)

Tags: of代码用户程序数量数字amountbug
3条回答

您没有将bugs collected today添加到bugs的整个集合中

您可以添加一个外部变量bugs = 0

并编辑while后的第一行:

bugs = int(input('enter the amount of bugs collected today:')) + bugs

整个代码如下所示:

^{pr2}$

假设你把所有的bug都列在一个列表中

weekly_bugs = [12, 42, 52, 52, 23, 75, 34]

你可以用一个基本方程很容易地求出平均值。在

^{pr2}$

如果您坚持使用while循环,可以执行以下操作:

sum_bugs = 0
while(weekly_bugs):
    sum_bugs += weekly_bugs.pop()

sum_bugs/len(weekly_bugs)

你要做的是从循环中的每个值中得到平均值。您应该将所有值相加,然后计算平均值,即:

i = 1

total = 0
for i in range(7):
    bugs = int(input('enter the amount of bugs collected today:'))
    total += bugs

average = total / 7
print('average amount of bugs collected in a week is:', average)

顺便说一句,在这种情况下使用for循环更加优雅!在

相关问题 更多 >

    热门问题