简体   繁体   English

如何以用户输入结束循环,但不将其计入数字的总体平均值

[英]How to end loop with user input but not count it in the overall average of the numbers

I am currently studying C++ but my friend sometimes sends me his past papers from his python studies so that I can try them out. 我目前正在学习C ++,但我的朋友有时会把他过去的python研究论文发给我,以便我可以尝试一下。 I am currently having a small problem with one of the final questions. 我目前对最后一个问题有一个小疑问。 I must add and find the average of the numbers entered and end the loop when the user enters a certain number eg:-200. 我必须添加并找到输入数字的平均值,并在用户输入某个数字(例如:-200)时结束循环。

I managed to find the average but it includes the -200 in the average and how many numbers where entered. 我设法找到了平均值,但平均值中包含-200,并输入了多少个数字。 I tried breaking the loop before it adds the -200 to the list and I tried adding 200 after its been added to the loop but it they both did not work. 我尝试在将-200添加到列表之前中断循环,并在将200添加到循环后尝试添加200,但是它们都没有作用。
This is what I have so far: 这是我到目前为止的内容:

avg = []
count = 0
while True:
    x = float(input('Enter a number(interger or float) :'))
    avg.append(x)
    count +=1

    if x == -999:

        list = avg 
        sum(list)
        len(list)
        avg = float(sum(list))/len(list)
        print ('The average of', count, 'is ' "%0.2f" % avg)
        break

Try this 尝试这个

avg = []
count = 0
while True:
    x = float(input('Enter a number(interger or float) :'))
    if x == -999:
        list = avg 
        sum(list)
        len(list)
        avg = float(sum(list))/len(list)
        print ('The average of', count, 'is ' "%0.2f" % avg)
        break
    else:
        avg.append(x)
        count +=1

You just need to add the number to the list to be averaged after you have checked whether its the terminating number. 您只需要在检查了其终止号之后,就将其添加到要求平均值的列表中即可。 You might not even need to put an else here since you are using break 您可能甚至不需要在此处放置else ,因为您正在使用break

Another option is reading the first value before entering the loop: 另一个选择是在进入循环之前读取第一个值:

numbers = []
numbers.append(float(input('Enter a number(interger or float) :')))
#the last argument given is the one you check for exeting the loop
while avg[-1] != -999:
    numbers.append(float(input('Enter a number(interger or float) :')))
length = len(numbers)
avg = float(sum(numbers)/length)
print ('The average of', str(length) , 'is ' "%0.2f" % avg)

not sure if this is better but it is an option if you want to avoid checking the if statement every iteration 不知道这是否更好,但是如果您希望避免每次迭代都检查if语句,则可以选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM