首页 > 解决方案 > 有没有办法在函数中输入多个数字,但是当输入 0 时脚本开始

问题描述

我正在尝试制作一个脚本,让您输入数字,直到输入 0,然后它将计算除 0 之外已输入的数字的算术平均值或平均值。这是我到目前为止所拥有的:

a=int(input())
b=0
d=0
while a!=0:
    c=int(input())
    d+=1
    if c !=0:
        break
b=a+c
average=b/c

print(average)

这个问题是它只允许我输入 2 个值。我在这里先向您的帮助表示感谢。

标签: pythonmathaverage

解决方案


你为什么不尝试一些更简单的东西?

a=float(input()) # enter the first input value, it can be also zero
avr=0
t=0 # enter the counter to measure the number of entries
while(a!=0): # you will stop if "a" is a zero
    # if you are here "a" is not zero, so we
    # can add it to the cumulative sum
    avr+=a
    t+=1 # increase the counter
    # re enter the input, if zero the loop will stop without
    # at the next iteration without changing the cumulative sum or the counter
    a=float(input())

# now to avoid division by zero (in case you entered zero as first value), we
# need an if to print out the results
if(t>0):
  print("mean value{}".format(avr/t))

推荐阅读