3 ms·
In my experience, when looking at how division should operate for a given well-established language, it doesn’t matter what you and I think should be the result
by strenholme 5y ago
In my experience, when looking at how division should operate for a given well-established language, it doesn’t matter what you and I think should be the result of the operation; it matters what the standard says on it.
From PDF page 94 (physical page 82) of the draft C99 standard: [1] The result of the / operator is the quotient from the division of the first operand by the second
This is a little vague; it would be better if they called it the “quotient from Euclidean division” (EDIT: This was incorrect. Actually, it’s the quotient from algebraic division, with the fraction truncated, also called “truncation towards zero”. See discussion below.), which is well defined as being -3 in the above example; see https://en.wikipedia.org/wiki/Euclidean_division https://en.wikipedia.org/wiki/Euclidean_division (EDIT: Euclidean is -4; truncation towards 0 is -3)
[1] http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
- naniwaduni 5y agoEuclidian division actually gives -7 = -4*2 + 1
- strenholme 5y agoIt’s -3 in GCC 11.2.0 main() { printf("%d\n",-7/2);} Let’s look at, oh, C11: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf PDF page 110, physical page 92: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. with a footnote: This is often called ‘‘truncation toward zero’’ -7/2 is -3.5, so discarding the fractional part gives us -3
- naniwaduni 5y agoYes, and this is not Euclidean division in the usual sense.
- strenholme 5y agoIndeed. The C99 and C11 standards define integer division as the “algebraic quotient with any fractional part discarded”, not as Euclidean division.
- GreenWatermelon 5y agoThis whole thread is a nice review and excersize of the 2nd chapter of my Computers and networks security course.
- wruza 5y agoit doesn’t matter what you and I think should be the result of the operation; it matters what the standard says on it In practice, this offloads the problem to your programmer in at least every other case (i.e. when % doesn’t what they need out of box), who then miscalculates or mistests their solution and now the problem is yours. It doesn’t matter what the standard says, there should be many functions, each for a combination of signs (or roundings) you want in the results. Because your library doesn’t suck and your programmer has things to do instead of fiddling with off by ones and other primitive but highly error-prone-under-stress bs.