我刚刚开始编写代码,卡在解决这个Python问题上。

huangapple go评论88阅读模式
英文:

I have just started coding and am stuck solving this python problem

问题

这是我迄今为止的代码:

  1. num = 0
  2. total_sum = 0
  3. while True:
  4. number = float(input("请输入一个数字:"))
  5. if number == -1:
  6. break
  7. total_sum += number
  8. num += 1
  9. if num > 0:
  10. avg = total_sum / num
  11. print("平均值是:", avg)
  12. else:
  13. print("没有输入有效的数字,无法计算平均值。")

这段代码将一直要求用户输入数字,直到用户输入-1为止。然后,它将计算输入的数字的平均值(不包括-1),并将结果显示出来。

英文:

> Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.

This is what I have come up with so far

  1. num = int(input("How many number's are there?"))
  2. total_sum = 0
  3. avg = total_sum / num
  4. for n in range (num):
  5. number = float(input("Enter a number"))
  6. while number <0:
  7. print = ("Average is", avg)
  8. number >0
  9. print(number)
  10. total_sum += number
  11. avg = total_sum / num
  12. print = ("Average is", avg)

I need it to stop at -1 one and still give an average of the numbers listed.

答案1

得分: -1

以下是代码部分的翻译:

  1. Easy.
  2. emp = []
  3. while True:
  4. ques = int(input("Enter a number: "))
  5. if ques != -1:
  6. emp.append(ques)
  7. continue # continue makes the code go back to beginning of the while loop
  8. else:
  9. if len(emp) != 0:
  10. avg = sum(emp) / len(emp) # average is the sum of all elements in the list divided by the number of elements in said list
  11. print(f"Average of all numbers entered is {avg}")
  12. break
  13. else:
  14. print("Give me at least one number that's not -1")
  15. continue # emp is empty we need at least one number to calculate the average so we go back to the beginning of the loop

希望这对你有所帮助。如果你有任何其他问题,或需要进一步的翻译,请随时告诉我。

英文:

Easy.

  1. emp = []
  2. while True:
  3. ques = int(input("Enter a number: "))
  4. if ques != -1:
  5. emp.append(ques)
  6. continue # continue makes the code go back to beginning of the while loop
  7. else:
  8. if len(emp) != 0:
  9. avg = sum(emp) / len(emp) # average is the sum of all elements in the list divided by the number of elements in said list
  10. print(f"Average of all numbers entered is {avg}")
  11. break
  12. else:
  13. print("Give me at least one number that's not -1")
  14. continue # emp is empty we need at least one number to calculate the average so we go back to the beginning of the loop

huangapple
  • 本文由 发表于 2023年2月16日 06:29:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定