python-3.x while循环的平均结果不一致

toiithl6  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(140)

我的程序接受用户的输入,计算字符串中的字母数,将它们添加到一个变量中,然后将该变量的总数除以输入的单词数,得到平均值。我发现我得到的平均值不一致。我做错了什么?

word_length_count = 0
count = 0
average = 0

word = input("Enter a word (press Enter to quit): ")
count = count + 1
word_length_count = round(word_length_count + len(word))
average = len(word)
while count == 1:
    word = input("Enter a word (press Enter to quit): ")
    if word == "":
        break
    else:
        while word != "":
            word = input("Enter a word (press Enter to quit): ")
            count = count + 1
            word_length_count = round(word_length_count + len(word))
            average = round(word_length_count / count)

print("The average length of the words entered is", round(average))
kiz8lqtg

kiz8lqtg1#

round()整数值没有意义(字符串长度不能是小数)。这里没有太多的嵌套循环,因为它没有任何用途,所有都可以在一个中处理。更不用说else的使用可以删除,因为这是简单的逻辑,如果满足条件,则脚本循环终止,因此没有点:

word_length_count = 0
count = 0

while True:
    word_len = len(input("Enter a word (press Enter to quit): "))
    if word_len == 0:
       break
    count += 1
    word_length_count += word_len

if count > 0:
    average = word_length_count / count
    print(f"The average length of the {count} words entered is {average:.2f}")
else:
    print("No words were entered.")

相关问题