Python平均测试s

2024-06-01 06:36:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个程序,将确定平均数的测试。测试的数量将有所不同,但我不希望它最初由用户输入设置。我想使用while循环和0的sentinel值来停止输入。我希望平均数显示到小数点后三位,最后一位后面紧跟%符号,如下所示。。。 样本运行: 输入测试分数80 输入测试分数70 输入测试分数90 输入测试分数88 输入测试分数0 平均为82.000%

total =0
counter = 0

while True:
    entry = int(input('Enter test score:'))
    if entry ==0:
        break

    total += entry
    counter += 1
    average = (total/counter)

 print("The average score:",format(average, '.3f'),'%',sep='') 

Tags: 用户程序数量counter符号分数sentineltotal
3条回答

While必须全部小写。

if entry == 0缺少冒号。

total += entrycounter += 1需要在循环中,因为它们必须在每次迭代中发生。

你试过运行你在这里发布之前的代码吗?

我至少看到了这两种选择: 一。将值存储在数组中,然后在循环之后计算平均值。 2。迭代计算每个循环的平均值

如果你期望大量的输入,我会选择(2)。

关于格式,这可能有帮助:https://docs.python.org/3/library/string.html#formatstrings

total = 0
counter = 0

while True:
    entry = int(input("Enter Test score: "))
    if entry == 0: break
    total += entry   # this should be in while loop
    counter += 1

total = total * 1.0
if counter == 0: exit(1)
avg = total / counter
print("Average is: %3.f" % avg + '%')

total++entry应该在while循环中,因为您想为每个接收到的条目添加它。 希望有帮助:)

相关问题 更多 >