英文:
I have just started coding and am stuck solving this python problem
问题
这是我迄今为止的代码:
num = 0
total_sum = 0
while True:
number = float(input("请输入一个数字:"))
if number == -1:
break
total_sum += number
num += 1
if num > 0:
avg = total_sum / num
print("平均值是:", avg)
else:
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
num = int(input("How many number's are there?"))
total_sum = 0
avg = total_sum / num
for n in range (num):
number = float(input("Enter a number"))
while number <0:
print = ("Average is", avg)
number >0
print(number)
total_sum += number
avg = total_sum / num
print = ("Average is", avg)
I need it to stop at -1 one and still give an average of the numbers listed.
答案1
得分: -1
以下是代码部分的翻译:
Easy.
emp = []
while True:
ques = int(input("Enter a number: "))
if ques != -1:
emp.append(ques)
continue # continue makes the code go back to beginning of the while loop
else:
if len(emp) != 0:
avg = sum(emp) / len(emp) # average is the sum of all elements in the list divided by the number of elements in said list
print(f"Average of all numbers entered is {avg}")
break
else:
print("Give me at least one number that's not -1")
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.
emp = []
while True:
ques = int(input("Enter a number: "))
if ques != -1:
emp.append(ques)
continue # continue makes the code go back to beginning of the while loop
else:
if len(emp) != 0:
avg = sum(emp) / len(emp) # average is the sum of all elements in the list divided by the number of elements in said list
print(f"Average of all numbers entered is {avg}")
break
else:
print("Give me at least one number that's not -1")
continue # emp is empty we need at least one number to calculate the average so we go back to the beginning of the loop
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论