【问题标题】:we need to write a prorgam that asks a user to enter multiple numbers and ends the while loop with -1.then work out the average of numbers provided我们需要编写一个程序,要求用户输入多个数字并以 -1 结束 while 循环。然后计算出所提供数字的平均值
【发布时间】:2022-01-12 07:24:38
【问题描述】:

我们的任务是用 python 编写一个程序,要求用户输入多个数字。 主题是while循环,所以我们只能使用while循环和if语句。 当用户想停止输入数字时,用户需要输入'-1'。 一旦完成,程序必须返回用户输入数字的平均值。

这是我目前所拥有的: #task 13-while.py

 #first the program will explain to the user that the user can keep
#entering numbers until -1 occurs.



  num = int(input('''please enter any number of your choice\n
  please enter -1 to stop entry and run program'''))

num_count = 0
while num > -1:
num_count = num_count + 1
average = sum(num)/num_count

if num == -1:
print("the average of the numbers you have entered is"+ average)

对python非常缺乏经验,非常感谢所有帮助。

【问题讨论】:

    标签: python input while-loop


    【解决方案1】:

    您需要将输入放入 while 中,然后仅在循环结束时计算平均值
    像这样:

    num = int(input("enter numbers and then -1 to stop: "))
    num_count = 1
    sum = num
    while num!=-1:
        num = int(input("another number: "))
        num_count+=1
        sum+=num
    print(sum/num_count)
    

    【讨论】:

      【解决方案2】:

      为了让它工作,您需要在while 循环中添加一个input() 调用,如下面的代码所示:

      count = 0
      sum = 0
      num = int(input('''please enter any number of your choice\n
      please enter -1 to stop entry and run program\n'''))
      
      while num != -1:
          sum += num
          count +=1
          num = int(input('''Give another integer\n'''))
      
      
      print("the average of the numbers you have entered is", sum/count)
      

      个人建议:我建议您阅读更多教程或向您的同行咨询更多工作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        • 1970-01-01
        相关资源
        最近更新 更多