How To Find The Average Of Numbers Being Input, With 0 Breaking The Loop?
Solution 1:
It seems to me that you need to keep a counter which tells you how many numbers the user has input so you can divide by it to get the average (being careful not to count the final 0). As an aside, the user can never put in 5,0,5,5
here because at the first 0, the loop will break and the other 2 5's won't have an opportunity to be input.
Solution 2:
The way to do average is to track "sum" of all the numbers and "# items" and divide the two when you're done.
So something like this:
nCount = 0
nSum = 0
nA = 1print ('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
Solution 3:
It's not really clear what you want to do: Do you want to use 0 as the condition to exit the loop, or do you just want to skip all the zeros?
For the first case (which I understand from the title of your question), can be done something like this:
total = 0
nums = 0
readnum = Noneprint("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 + 1print'total amount of numbers is %d' % (nums)
print'avg is %f' % (float(total)/nums)
The float
on the division is needed otherwise the division is done only using the integer parts (e.g. the average of 1, 3 and 4 will give 2, not 2.66667).
It should be simple enough to adapt for the second case.
Post a Comment for "How To Find The Average Of Numbers Being Input, With 0 Breaking The Loop?"