Program not entering if statement

后端 未结 7 1841
走了就别回头了
走了就别回头了 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:30

    Others have pointed out the issue with floating-point numbers being unable to represent values exactly. If you need exact decimal representation of a number, you can use the Decimal class:

    from decimal import Decimal
    
    x = Decimal(-5)
    while x < 5:
        if (x == 0):
            print 0
        x += Decimal(".01")
    

    This will print 0 as you expect.

    Note the use of a string for the increment. If you used Decimal(.01) you'd have the same problem with accurate representation of 0.01, because you're converting from a floating-point number and have already lost the accuracy, so the class doesn't allow that.

提交回复
热议问题