Back to index

glibc  2.9
ldiv.c
Go to the documentation of this file.
00001 /* Copyright (C) 1992, 1997 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Lesser General Public
00006    License as published by the Free Software Foundation; either
00007    version 2.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C Library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Lesser General Public License for more details.
00013 
00014    You should have received a copy of the GNU Lesser General Public
00015    License along with the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 #include <stdlib.h>
00020 
00021 
00022 /* Return the `ldiv_t' representation of NUMER over DENOM.  */
00023 ldiv_t
00024 ldiv (long int numer, long int denom)
00025 {
00026   ldiv_t result;
00027 
00028   result.quot = numer / denom;
00029   result.rem = numer % denom;
00030 
00031   /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
00032      NUMER / DENOM is to be computed in infinite precision.  In
00033      other words, we should always truncate the quotient towards
00034      zero, never -infinity.  Machine division and remainer may
00035      work either way when one or both of NUMER or DENOM is
00036      negative.  If only one is negative and QUOT has been
00037      truncated towards -infinity, REM will have the same sign as
00038      DENOM and the opposite sign of NUMER; if both are negative
00039      and QUOT has been truncated towards -infinity, REM will be
00040      positive (will have the opposite sign of NUMER).  These are
00041      considered `wrong'.  If both are NUM and DENOM are positive,
00042      RESULT will always be positive.  This all boils down to: if
00043      NUMER >= 0, but REM < 0, we got the wrong answer.  In that
00044      case, to get the right answer, add 1 to QUOT and subtract
00045      DENOM from REM.  */
00046 
00047   if (numer >= 0 && result.rem < 0)
00048     {
00049       ++result.quot;
00050       result.rem -= denom;
00051     }
00052 
00053   return result;
00054 }