0

I always thought '//' in python is same as '/' in c++. if I do cout<<-5/2; in c++, it gives -2. But in python if I try print(-5//2) it gives -3. why is this happening? aren't they both the same.?

  • 2
    You have encountered one of the ways they are not exactly the same. Yes, in Python `//` will perform integer division, but Python's behavior for rounding negative numbers differs from C++'s. In general there are very few things in programming languages that are *exactly* the same as things in other programming languages. – Nathan Pierson Feb 18 '22 at 16:18
  • If the results are different, they are clearly not the same. – molbdnilo Feb 18 '22 at 16:19
  • 1
    C++ rounds integer division towards 0, producing `-2`. Python rounds toward -infinity, producing `-3`. Neither language "gives 3". – Drew Dormann Feb 18 '22 at 16:20
  • Python's '//' operator performs "floor division", not "integer division". Simple as that. – Tasos Papastylianou Feb 18 '22 at 16:22
  • Also "What's the mathematical reason behind Python choosing to round integer division toward negative infinity?" is a good example of the Bulverism fallacy (in that this is not what is happening, so assuming it is and then asking 'why' is fallacious). The linked answer is not a good answer. – Tasos Papastylianou Feb 18 '22 at 16:29
  • 1
    The equivalent in Python is: print(math.trunc(-5 / 2)) – Dave Doknjas Feb 18 '22 at 16:59
  • *why is this happening?* Because what you had always thought was actually mistaken. *aren't they both the same?* No, as empirically demonstrated. – Eljay Feb 18 '22 at 17:04
  • I am tempted to answer: because Python is 20 years younger than C, so it fixes some conceptual mistakes from earlier languages. – prapin Feb 18 '22 at 20:35

0 Answers0