取几个数字并给出数字的平均值

Take a few numbers and give the average of the numbers

我想从用户那里得到一些数字,这样直到用户按下数字 -1 为止。打到数字-1后,程序会给他之前数字的平均值。我的代码有效但错误计算了平均值。有什么问题?

  sum = 0
  count = 0 
  x = []
  while x != -1 :
      x = int(input())
      sum += x
      count += 1

  averagex = sum / count 
  print(averagex)


   

您的循环在 用户输入 -1 终止。这意味着在最后一次迭代中,将从总数中减去 1,并且 count 将比应有的高一个。试试这个:

  while True:
      x = int(input())
      if x == -1:
          break
      sum += x
      count += 1

现在你的输入验证是在 while x != -1 完成的,它在 输入、总和和计数部分之后执行,所以 -1 将是结果的一部分,你不想要的东西。

一个简单的 if 将解决这个问题:

total, count, x = 0, 0, 0
while True:
    x = int(input("Enter a value: "))
    if x == -1:
        break
    total += x
    count += 1

避免使用内置函数名称,例如 sum,用于变量命名