如何计算 python 2.7 的平均值
How to calculate average / mean on python 2.7
我正在尝试计算用户输入数字并在他决定时停止的平均值。我设法得到了总和,但是我不能将它除掉,因为我需要以某种方式在他停止输入之前得到输入的数量。到目前为止,这是我的代码:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = 0
x = raw_input ('please enter the number')
while (num != 'f'):
x = eval (x)
s = s + x
x = raw_input ('please enter the number')
print (' the average is'), s
就像你看到的那样,我设法得到了总和,但是我不知道如何得到输入的数量,然后将总和除以这个得到平均值。任何帮助将不胜感激
您只需要在 while 循环中添加一个计数器:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = i = 0 #declare counter: i = 0
x = raw_input ('please enter the number')
while (x != 'f'):
x = eval (x)
s = s + x
i+=1 #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
x = raw_input ('please enter the number')
print (' the average is'), s/i #divide the sum by counter
我正在尝试计算用户输入数字并在他决定时停止的平均值。我设法得到了总和,但是我不能将它除掉,因为我需要以某种方式在他停止输入之前得到输入的数量。到目前为止,这是我的代码:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = 0
x = raw_input ('please enter the number')
while (num != 'f'):
x = eval (x)
s = s + x
x = raw_input ('please enter the number')
print (' the average is'), s
就像你看到的那样,我设法得到了总和,但是我不知道如何得到输入的数量,然后将总和除以这个得到平均值。任何帮助将不胜感激
您只需要在 while 循环中添加一个计数器:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = i = 0 #declare counter: i = 0
x = raw_input ('please enter the number')
while (x != 'f'):
x = eval (x)
s = s + x
i+=1 #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
x = raw_input ('please enter the number')
print (' the average is'), s/i #divide the sum by counter