首页 > 解决方案 > Python 浮点数转换

问题描述

我的教授在演示期间编写了第二个代码片段。他们的输出是一个浮点数。对我来说,只有第一个代码片段是浮点数。知道为什么会有区别吗?第二个代码片段似乎有整数除以整数,添加到整数,所以我不确定为什么它被转换为浮点数。

n = 4
total = 0
for i in range(n+1):
  total = total + 1 / float(2**i)
return total
n = 4
total = 0
for i in range(n+1):
  total = total + 1 / 2**i
return total

标签: python

解决方案


正如 khelwood 所提到的,在 Python 2 中,当您将整数与整数相除时,结果也是integer,但在 Python 3 中,结果变为float。让我演示一下

蟒蛇2

# 10/6 == 1
# 10/3 == 3

很像 C++ 的除法运算符,它删除任何小数值并返回一个整数。然而,这对 Python 3 有所改变

蟒蛇 3

#10/6 == 1.6666666666666667
#10/3 == 3.3333333333333335

在 python 3 中,除法运算符将返回 float(dividing int/int)

如果你想在 Python 2 中进行浮点除法,你需要 from __future__ import division像 Jan 提到的那样。

这将让你除以得到一个浮点值


推荐阅读