xref: /csrg-svn/lib/libc/stdlib/div.c (revision 42131)
1*42131Sbostic /*
2*42131Sbostic  * Copyright (c) 1990 Regents of the University of California.
3*42131Sbostic  * All rights reserved.
4*42131Sbostic  *
5*42131Sbostic  * This code is derived from software contributed to Berkeley by
6*42131Sbostic  * Chris Torek.
7*42131Sbostic  *
8*42131Sbostic  * %sccs.include.redist.c%
9*42131Sbostic  */
10*42131Sbostic 
11*42131Sbostic #if defined(LIBC_SCCS) && !defined(lint)
12*42131Sbostic static char sccsid[] = "@(#)div.c	5.1 (Berkeley) 05/16/90";
13*42131Sbostic #endif /* LIBC_SCCS and not lint */
14*42131Sbostic 
15*42131Sbostic #include <stdlib.h>		/* div_t */
16*42131Sbostic 
17*42131Sbostic /*
18*42131Sbostic  * I AM NOT SURE THIS IS COMPLETELY PORTABLE
19*42131Sbostic  * (or that it is even right)
20*42131Sbostic  */
21*42131Sbostic div_t
22*42131Sbostic div(num, denom)
23*42131Sbostic 	int num, denom;
24*42131Sbostic {
25*42131Sbostic 	div_t r;
26*42131Sbostic 
27*42131Sbostic 	/* avoid deep thought */
28*42131Sbostic 	if (num > 0 && denom < 0) {
29*42131Sbostic 		num = -num;
30*42131Sbostic 		denom = -denom;
31*42131Sbostic 	}
32*42131Sbostic 	r.quot = num / denom;
33*42131Sbostic 	r.rem = num % denom;
34*42131Sbostic 	if (num < 0 && denom > 0) {
35*42131Sbostic 		/*
36*42131Sbostic 		 * Machine division and remainer may work either way.  The
37*42131Sbostic 		 * ANSI standard says that |r.quot| < |n/d| (where n/d
38*42131Sbostic 		 * computed in infinite precision).  If the remainder is
39*42131Sbostic 		 * positive, we got the `wrong' answer, so fix it.
40*42131Sbostic 		 */
41*42131Sbostic 		if (r.rem > 0) {
42*42131Sbostic 			r.quot++;
43*42131Sbostic 			r.rem -= denom;
44*42131Sbostic 		}
45*42131Sbostic 	}
46*42131Sbostic 	return (r);
47*42131Sbostic }
48