In C , when both numerator and denominator are integers and of same sign , then division operator gives the floor value of the quotient . But when they are of opposite sign , then it gives ceil value . Is my understanding correct or is there more to it ?
CodePudding user response:
You have it right. Some 20th-century hardware engineer decided to do it this way, and as far as I know this is how all microprocessors now natively do it. Mathematically, it's often a little inconvenient, which is why Python (for example) corrects in software always to round toward toward floor.
For additional insight, besides p/q
for an integer quotient, try p%q
for the corresponding remainder.
Your question is tagged C but this is really a computer hardware issue and, as such, it may be more helpful to consult the C17 standard, whose sect. 6.5.5(6) reads:
When integers are divided, the result of the
/
operator is the algebraic quotient with any fractional part discarded. If the quotienta/b
is representable, the expression(a/b)*b a%b
shall equala
....
(I have a shred of a memory from 25 or 30 years ago, reading about a CPU that rounded toward floor. If my memory is not altogether imaginary, then that CPU apparently did not succeed in the marketplace, did it?)