Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is -1/2 evaluated to 0 in C++, but -1 in Python?

  • C++: cout << -1/2 evaluates to 0
  • Python: -1/2 evaluates to -1.

Why is this the case?

like image 483
Chao Xu Avatar asked Sep 18 '25 16:09

Chao Xu


2 Answers

Integer division in C++ rounds toward 0, and in Python, it rounds toward -infinity.

People dealing with these things in the abstract tend to feel that rounding toward negative infinity makes more sense (that means it's compatible with the modulo function as defined in mathematics, rather than % having a somewhat funny meaning). The tradition in programming languages is to round toward 0--this wasn't originally defined in C++ (following C's example at the time), but eventually C++ (and C) defined it this way, copying Fortran.

like image 177
Mike Graham Avatar answered Sep 20 '25 05:09

Mike Graham


From the Python docs (emphasis mine):

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.

The floor function rounds to the number closest to negative infinity, hence -1.

like image 21
SethMMorton Avatar answered Sep 20 '25 04:09

SethMMorton