python - 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
解决方案
正如 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 提到的那样。
这将让你除以得到一个浮点值
推荐阅读
- javascript - 使用 JS 的数组映射 - 将值与另一个数组进行比较并从第二个数组返回值
- regex - 匹配除正斜杠以外的任何字符
- css - 悬停时引导列放大(如 Netflix)
- javascript - 使用 java 脚本转到页面的一部分
- html - 做什么
- c - kaprekar 数字计算失败超过两位数
- java - 我们可以在不循环的情况下将地图数组转换为模型实体类[POJO]的数组吗?
- android - 将我的 ionic 应用程序 apk 上传到 Google Play 控制台时出错
- php - 检查已经存在的用户名或不是 MySQL,PHP
- oracle - 验证在 oracle apex 的页面提交上不起作用