Python 上的 Int vs Double

Int vs Double on Python

我现在在统计 class,我想知道一次生成一个数字与一次生成一个数字是否有区别,所以我写了一些代码.. .

from random import randint
import math

total1 = 0
total2 = 0
for i in range(100000):
    temp = 0
    for j in range(7):
        temp += randint(0,9)*math.pow(10,j)
    total1 += temp
    total2 += randint(0,9999999)

print "avg1 = ", total1/100000
print "avg2 = ", total2/100000

当我 运行 代码时,avg1 始终是小数,avg2 始终是整数。我不明白为什么 total1 被认为是双精度数,因为我只向它添加了整数...

根据 python 文档,math.pow 函数 return 是一个浮点数。这也将隐式地将临时变量转换为浮点数:

https://docs.python.org/2/library/math.html

因为 total1 被隐式转换为浮点数,而 total2 一直被用作 int,total1 将 return 一个小数,而 total2 将 return 一个整数。