奇怪的 python while 循环行为 <比较

编程入门 行业动态 更新时间:2024-10-18 12:29:19
本文介绍了奇怪的 python while 循环行为 <比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我对这段代码感到困惑:

I'm confused with this snippet of code:

t=0
while  t<5:  #currently loop runs for 10 seconds
    print "in loop",t
    if (t<5):
        print "true"
    t=t+0.01

在循环的最后一次运行中打印:

prints in the last run through of the loop:

in loop 5.0 
true

现在,如果在最后一次通过循环时 t = 5.0 是真的,那么 t < 不应该是条件.5 在if 语句中不被满足?此外,它不应该甚至不运行 t=5 的循环,因为它也应该在 while 条件下失败吗?

Now if it is true that t = 5.0 on the last pass through the loop, shouldn't the condition that t < 5 in the if statement not be met? And furthermore, shouldn't it not even be running through the loop for t=5 since it should have also failed the while condition?

推荐答案

5 不一定是 5:

t=0
while  t<5:  #currently loop runs for 10 seconds
    print "in loop",t, repr(t)
    if (t<5):
        print "true"
    t=t+0.1

生产

in loop 0 0
true
in loop 0.1 0.1
true
in loop 0.2 0.2
true
in loop 0.3 0.30000000000000004

[...]

in loop 4.8 4.799999999999999
true
in loop 4.9 4.899999999999999
true
in loop 5.0 4.999999999999998
true

0.1 不能用二进制精确表示.

0.1 can't be represented exactly in binary.

[啊,我刚刚注意到我用的是 0.1 而不是 0.01,就像你一样.嗯,这是同样的问题.]

[Ah, I just noticed that I used 0.1 instead of 0.01, like you did. Well, it's the same issue.]

两个浮点工作原理"参考:经典 和 绅士.

Two "how floating point works" references: classical and gentler.

这篇关于奇怪的 python while 循环行为 &lt;比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:30:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128617.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:奇怪   python   lt   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!