What is the difference between '/' and '//' when used for division?

后端 未结 13 2151
孤独总比滥情好
孤独总比滥情好 2020-11-21 07:23

Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:

>>> 6/3
2
>>> 6//3
2
相关标签:
13条回答
  • 2020-11-21 07:36
    >>> print 5.0 / 2
    2.5
    
    >>> print 5.0 // 2
    2.0
    
    0 讨论(0)
  • 2020-11-21 07:36

    The answer of the equation is rounded to the next smaller integer or float with .0 as decimal point.

    >>>print 5//2
    2
    >>> print 5.0//2
    2.0
    >>>print 5//2.0
    2.0
    >>>print 5.0//2.0
    2.0
    
    0 讨论(0)
  • 2020-11-21 07:40
    • // is floor division, it will always give you the floor value of the result.
    • And the other one / is the floating-point division.

    Followings are the difference between / and //; I have run these arithmetic operations in Python 3.7.2

    >>> print (11 / 3)
    3.6666666666666665
    
    >>> print (11 // 3)
    3
    
    >>> print (11.3 / 3)
    3.7666666666666667
    
    >>> print (11.3 // 3)
    3.0
    
    0 讨论(0)
  • 2020-11-21 07:42

    // is floor division, it will always give you the integer floor of the result. The other is 'regular' division.

    0 讨论(0)
  • 2020-11-21 07:43

    The above answers are good. I want to add another point. Up to some values both of them result in the same quotient. After that floor division operator (//) works fine but not division (/) operator.

     - > int(755349677599789174/2)
     - > 377674838799894592      #wrong answer
     - > 755349677599789174 //2
     - > 377674838799894587      #correct answer
    
    0 讨论(0)
  • 2020-11-21 07:44

    The double slash, //, is floor division:

    >>> 7//3
    2
    
    0 讨论(0)
提交回复
热议问题