Program not entering if statement

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

    This is a rounding issue - decimal values cannot be represented exactly in binary, so x never exactly equals 0.0000000000....

    try replacing if (x == 0): with if -0.001 < x < 0.001:

    BTW, the parentheses are unnecessary in a python if statement.

    edit: Printing out the values between -1 and 1 in steps of 0.01 shows this is the case - where zero should be it prints 7.52869988574e-16.

提交回复
热议问题