Python 通过while循环获得平均值
臭虫收集器每天收集臭虫七天。用Python编写一个程序,保持在七天内收集的bug数量的运行平均值。程序应该询问每天收集的bug数量,循环完成后,程序应该显示一周内收集的bug的平均数量 我试着运行我写的代码,但是它不能得到用户输入的所有数字的平均值。它只需要输入第一个数字,然后除以7。有人能告诉我我做错了什么吗Python 通过while循环获得平均值,python,Python,臭虫收集器每天收集臭虫七天。用Python编写一个程序,保持在七天内收集的bug数量的运行平均值。程序应该询问每天收集的bug数量,循环完成后,程序应该显示一周内收集的bug的平均数量 我试着运行我写的代码,但是它不能得到用户输入的所有数字的平均值。它只需要输入第一个数字,然后除以7。有人能告诉我我做错了什么吗 i = 1 while i < 8: bugs = int(input('enter the amount of bugs collected today:'))
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)
i=1
而我<8:
bugs=int(输入('输入今天收集的bugs数量:'))
平均值=错误/7
i+=1
打印('一周内收集的平均bug数量为:',平均值)
您没有将今天收集的bug添加到整个bug集合中
您可以添加外部变量bugs=0
并将之后的第一行编辑为:
bugs = int(input('enter the amount of bugs collected today:')) + bugs
整个代码如下所示:
i = 1
bugs = 0
while i < 8:
bugs = int(input('enter the amount of bugs collected today:')) + bugs
average = bugs / 7
i+=1
print('average amount of bugs collected in a week is:', average)
i=1
bug=0
而我<8:
bugs=int(输入('输入今天收集的bugs数量:')+bugs
平均值=错误/7
i+=1
打印('一周内收集的平均bug数量为:',平均值)
假设您将所有bug都保存在一个列表中
weekly_bugs = [12, 42, 52, 52, 23, 75, 34]
你可以用一个基本方程式很容易地找到平均数
avg_bug = sum(weekly_bugs)/7
如果坚持使用while循环,可以执行以下操作:
sum_bugs = 0
while(weekly_bugs):
sum_bugs += weekly_bugs.pop()
sum_bugs/len(weekly_bugs)
您所做的是从循环中的每个值中获取平均值。应将所有值相加,然后计算平均值,即:
i=1
总数=0
对于范围(7)中的i:
bugs=int(输入('输入今天收集的bugs数量:'))
总数+=错误
平均数=总数/7
打印('一周内收集的平均bug数量为:',平均值)
顺便说一句,在这种情况下使用for循环要优雅得多 除了错误的算法(已经被其他贡献者纠正)之外,代码中还有一堆非python模式。考虑使用列表理解和<代码> SUME()/<代码>函数。
DAYS = 7
bugs = [int(input('enter the amount of bugs collected today:'))
for _ in range(DAYS)]
average = sum(bugs) / DAYS
print('average amount of bugs collected in a week is:', average)
试试这个
days=7天
总数=0
平均错误=0
正在运行_avg=list()
对于范围内的i(天):
bugs=int(输入('输入今天收集的bugs数量:'))
总臭虫数+=臭虫数
平均缺陷=总缺陷/(i+1)
正在运行\u avg.append(avg\u bug)
打印('一周内收集的平均bug数量为:{}'。格式(平均bug))
您应该重新审视“平均”的定义。它是总和除以元素数。另外,由于您硬编码了列表的最终长度,因此您尝试执行的不是运行平均值。您希望这样做有什么作用?