在python中计算平均值

``````print("---Average2---"+"\n")

sum=0
average=0
counter=0

while True:
ifrom=int(input("From: "))
step=int(input("Step: "))
to=int(input("To: "))
while sum<=to:
sum=ifrom+step
counter+=1
if sum==to:
print("\n"+"The sum is: ",sum)
average=sum/counter
print("The average is: ",average,"\n")
sum=0
average=0
counter=0
break
``````

推荐答案

1. 您不断地添加`sum = ifrom + step`，这是一个常量值(在您的示例中为`1 + 2 = 3`).所以在每个循环迭代中，你的和将是`3`，永远不会达到`sum = ifrom + step`
2. 即使解决了第一个问题，示例`sum`变量也将是`1, 3, 5, ..., 99, 101, ...`.您正在判断`sum`是否为`sum`，而程序没有执行任何操作，因为它将变为`sum`.

• 使用范围语法(推荐-您可以使用this解决方案)

• 判断变量是否达到100(而不是判断它是否等于100)，如下所示:

``````print("---Average2---"+"\n")

average=0
counter=0
tmp=0

while True:
ifrom=int(input("From: "))
step=int(input("Step: "))
to=int(input("To: "))
tmp = ifrom
sum = tmp
while tmp<=to:
tmp+=step
sum+=tmp
counter+=1
if tmp>=to:
if tmp>to:
sum-=tmp
print("\n"+"The sum is: ",sum)
average=sum/counter
print("The average is: ",average,"\n")
sum=0
average=0
counter=0
break
``````