Why is this division not performed correctly?

前端 未结 3 1814

I\'ve a strange issue in Python: the division is not performed correctly:

print pointB[1]
print pointA[1]
print pointB[0]
print pointA[0]
print  (pointB[1]-         


        
相关标签:
3条回答
  • 2020-12-06 19:29

    It is done correctly.

    50/60 = 0

    Maybe you are looking for 50.0/60.0 = 0.83333333333333337, you can cast your variables to float to get that:

    print  float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
    
    0 讨论(0)
  • 2020-12-06 19:31

    The above behavior is true for Python 2. The behavior of / was fixed in Python 3. In Python 2 you can use:

    from __future__ import division
    

    and then use / to get the result you desire.

    >>> 5 / 2
    2
    >>> from __future__ import division
    >>> 5 / 2
    2.5
    

    Since you are dividing two integers, you get the result as an integer.

    Or, change one of the numbers to a float.

    >>> 5.0 / 2
    2.5
    
    0 讨论(0)
  • 2020-12-06 19:37

    This is how integer division works in python. Either use floats or convert to float in your calculation:

    float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
    
    0 讨论(0)
提交回复
热议问题