Python将n发现为101而不是100

时间:2016-08-07 12:52:33

标签: python conditional

Python循环发现n为101而不是100,我得到5050的平均值为50而不是50.50,可能是什么问题?我该怎么办呢?这是我的功能。

def sum_and_average(n):
    total = 0
    for i in range(1, n+1):
        total += i
    average = float(total/n)
    print "the sum is %d and the average is %f" %(total, average)

sum_and_average(100)

它返回:

the sum is 5050 and the average is 50.000000

2 个答案:

答案 0 :(得分:1)

要获得您想要的平均值:

average = float(total)/n

一些例子:

>>> float(101/2)
50.0
>>> 101/2
50
>>> float(101)/2
50.5

答案 1 :(得分:1)

执行float(total) / n

在Python 2中,当其中一个参数为float时,计算将在float中执行。

但是float(total/n)无效,因为total/n已经用整数计算,float结果已经太晚了。