问题
- C++:
cout << -1/2
evaluates to0
- Python:
-1/2
evaluates to-1
.
Why is this the case?
回答1:
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 rouding 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.
回答2:
For C++, from this reference: http://www.learncpp.com/cpp-tutorial/32-arithmetic-operators/
It is easiest to think of the division operator as having two different “modes”. If both of the operands are integers, the division operator performs integer division. Integer division drops any fractions and returns an integer value.
Thus, -1/2
would yield -0.5
with the fraction dropped, yielding 0
.
As @SethMMorton indicated, Python's rule is floor
, which yields -1
. It's described here: http://docs.python.org/2/reference/expressions.html.
Put in the terms that @MikeGraham mentioned, floor
is a round toward minus infinity. Dropping the fraction is a round toward zero.
回答3:
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.
回答4:
I am not sure about python but in C++ integer/integer = integer therefore in case of -1/2 is -0.5 which is rounded automatically to integer and therefore you get the 0 answer. In case of Python may be the system used the floor function to convert result into integer.
来源:https://stackoverflow.com/questions/22030342/why-is-1-2-evaluated-to-0-in-c-but-1-in-python