当输入为0时,如何求循环数的平均值?

2024-09-28 03:23:07 发布

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

我只需要弄清楚如何在使用0作为循环出口时,找到用户输入的所有这些数字的平均值。在

我需要找出如何消除使用0作为平均值的一部分。例如:5,0,5,5。。。通过消除0,平均值为5。在

nA = 1
nSum = 0
print ('enter numbers to find the average')
print ('enter 0 to quit.')
while nA !=0:
    nA = input ('gemmi a number:')
    nSum+=nA
   dAvg = nSum

print 'the total amount of numbers is' , nSum ,
print 'your average is' , dAvg , 

我该怎么做?在


Tags: theto用户is数字findquit平均值
3条回答

求平均值的方法是跟踪所有数字和“项目”的“和”,完成后将两者分开。在

所以像这样:

nCount = 0
nSum = 0
nA = 1
print ('enter numbers to find the average')
print ('enter 0 to quit.')
while nA != 0:
    nA = input ('gemmi a number:')
    if nA != 0:
      nCount = nCount + 1
      nSum = nSum + nA

dAvg = nSum / nCount
print 'the total amount of numbers is' , nCount
print 'your average is' , dAvg

在我看来,你需要保留一个计数器,它告诉你用户输入了多少个数字,这样你就可以除以它得到平均值(注意不要数到最后的0)。顺便说一句,用户永远不能把5,0,5,5放在这里,因为在第一个0,循环将中断,而其他25个将没有机会被输入。在

你到底想做什么还不清楚:你想用0作为退出循环的条件,还是只想跳过所有的0?在

对于第一个案例(我从你的问题标题中了解到),可以这样做:

total = 0
nums = 0
readnum = None
print("Enter numbers to find the average. Input 0 to exit.")

while readnum != 0:
    readnum = int(raw_input('>'))
    total = total + readnum
    if readnum != 0:
      nums = nums + 1

print 'total amount of numbers is %d' % (nums)
print 'avg is %f' % (float(total)/nums)

除法需要float,否则除法只使用整数部分(例如,1、3和4的平均值将得到2,而不是2.66667)。在

它应该足够简单,以适应第二种情况。在

相关问题 更多 >

    热门问题