python - 需要解释为什么以下代码跨越无穷大

标签 python python-3.x

我是 python 的初学者,想知道为什么代码应该停在 1 时却跨越无穷大。

def main():
    i = 0.0
    while i != 1.0:
        print("i =", i)
        i += 0.1
main()

最佳答案

This is a well known problem in Python.

你的变量i永远不会恰好变成1,而是变成0.9999999999999999。

改为:

def main():
    i = 0.0
    while i <= 1.0:
        print("i =", i)
        i += 0.1

关于python - 需要解释为什么以下代码跨越无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42889809/

相关文章:

emacs 中的 python 3

python - 在 Python3 的 Matplotlib 的极坐标/径向条形图中获取条形图顶部的标签

python - 如何为 python 安装 pjsua2 包?

python - Ruby:无法在 Windows 7 上安装 libv8:缺少 python 安装

python - 如何在 Mininet 中运行 sudo mn --custom 选项?

python http 客户端卡在 100 继续

python - 如果特定属性匹配,则查找并提取 xml 标签的名称

python-3.x - 属性错误 : type object 'h5py.h5.H5PYConfig' has no attribute '__reduce_cython__'

python - 将字符串转回日期时间 timedelta

python - 使用 python-pptx 打印 Powerpoint 幻灯片