While循环计数不正确

编程入门 行业动态 更新时间:2024-10-24 19:22:03
本文介绍了While循环计数不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最近两周我一直在学习python编程,到目前为止进展非常好.但是现在我被困住了,似乎找不到答案. 我发现while循环确实很怪异,只是无法缠住我的头.

I've been learning programming in python for the last two weeks and it's going great so far. But now I'm stuck and can't seem to find an answer. I found a really weird behaviour of a while loop, I just can't wrap my head around.

x=0 step_size=0.2 while x<2: print x x+=step_size

此代码显示:

0 0.2 0.4 ... 1.8 2.0

2.0不应该打印,对不对?当x变为2.0时,语句"x< 2"为假,因此循环应退出并且永远不打印2.0.

2.0 should not be printed, right? When x becomes 2.0 the statement "x<2" is false, therefore the loop should exit and never print 2.0.

现在,对于真正奇怪的部分:它可以与其他数字一起使用. Step_size = 0.4最多可打印1.6,step_size = 0.1最多可打印1.9. 使用"x< 1"作为语句,并且step_size = 0.2也可以.

And now for the really weird part: it works with other numbers. Step_size=0.4 prints up to 1.6, step_size=0.1 up to 1.9. Using "x<1" as a statement and step_size=0.2 also works.

我想念什么?

最诚挚的问候, 狮子座

Best regards, Leo

我正在使用python 2.7.5和默认的Idle Editior v2.7.5

I'm using python 2.7.5 and the default Idle Editior v2.7.5

推荐答案

它是浮点算法.在控制台上输出python 3.6

It's floating point arythmetic. Output in console for python 3.6

0 0.2 0.4 0.6000000000000001 0.8 1.0 1.2 1.4 1.5999999999999999 1.7999999999999998 1.9999999999999998

更多推荐

While循环计数不正确

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

发布评论

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

>www.elefans.com

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