div() & ldiv() behavior?

Stan Brown browns at iccgcc.decnet.ab.com
Tue Apr 16 06:49:15 AEST 1991


In article <10989 at ncar.ucar.edu>, steve at unidata.ucar.edu (Steve Emmerson) writes:
> Would someone who knows please tell me the behavior of div() and ldiv()?
> 
> I know what this means when both arguments are positive, but I'm uncertain
> what this means for the other three cases.  I you would tell me, I would

Sec 4.10.6.2 of the standard says that div(int numer, int denom)
"computes the quotient and  remainder of the division of the numerator
numer by the denominator denom.  If the division is inexact, the
resulting quotient is the integer of lesser magnitude that is nearest to
the algebraic quotient.  If the result [can] be represented, ... 
quot * denom + rem shall equal numer."

This means, as I read it, that the quotient is always truncated toward
zero.  Thus,
	div(8,3)   gives quot=2,  rem=2
	div(8,-3)  gives quot=-2, rem=2
	div(-8,3)  gives quot=-2, rem=-2
	div(-8,-3) gives quot=2,  rem=-2
There's a similar table in sec 4.10.6.2 of the rationale, with 7
substituted for 8 and 1's or -1's for the remainders.

BTW, note that this is may be different from the result of 8/(-3) etc.
Sec 3.3.5 says the result can be -2 or -3 (implementation-defined).

Stan Brown, Oak Road Systems, Cleveland, Ohio, USA    +1 216 371 0043
                   email (until 91/4/30): browns at iccgcc.decnet.ab.com
My opinions are mine:  I don't speak for any other person or company.



More information about the Comp.std.c mailing list