Program not entering if statement

后端 未结 7 1848
走了就别回头了
走了就别回头了 2021-01-19 05:01

In my python program, an if statement is not being entered. I have simplified the code to the following:

x = -5
while x < 5:
    if (x == 0):
        prin         


        
7条回答
  •  走了就别回头了
    2021-01-19 05:24

    In binary, .01 has no exact representation but .5 does.

    It's the same problem you'd have in decimal if you represented 1/3 as .333333 and kept adding 1/3 until you reached 1. After three additions, you'd have .999999 which is not exactly equal to 1.

    Don't compare non-integers for equality unless you precisely understand the rules for doing so and are 100% sure your case is one of the ones that will work.

提交回复
热议问题