home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16370 < prev    next >
Encoding:
Internet Message Format  |  1992-11-11  |  1.4 KB

  1. Path: sparky!uunet!ferkel.ucsb.edu!taco!rock!stanford.edu!ames!haven.umd.edu!darwin.sura.net!zaphod.mps.ohio-state.edu!caen!batcomputer!munnari.oz.au!goanna!ok
  2. From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Rounding floats to integers
  5. Message-ID: <15905@goanna.cs.rmit.oz.au>
  6. Date: 12 Nov 92 03:44:26 GMT
  7. References: <92314.134711IA8@psuvm.psu.edu>
  8. Organization: Comp Sci, RMIT, Melbourne, Australia
  9. Lines: 33
  10.  
  11. In article <92314.134711IA8@psuvm.psu.edu>, IA8@psuvm.psu.edu (Alan R. Heyd) writes:
  12. > Is there a C routine that will round off floating point numbers
  13. > to the nearest integer.
  14.  
  15. C directly supports three ways of converting a float to an integer:
  16.  
  17.     #include <math.h>
  18.     int i;
  19.     double x;
  20.     
  21.     i = x;            /* truncate */
  22.     i = floor(x);        /* floor */
  23.     i = ceil(x);        /* ceiling */
  24.  
  25. Note that in the latter two, TWO conversions are involved:  double ->
  26. integer in double format -> integer.
  27.  
  28. C does _not_ include a round-to-nearest integer function.  Many
  29. implementations have one, but the names vary.  rint() is one of those names.
  30.  
  31. > What I do now is add 0.5 to the float before it is converted to
  32. > an integer, for example:
  33. >           i = 6.0 / 0.3;         /*   i = 19                     */
  34. >           i = 6.0 / 0.3 + 0.5;   /*   i = 20 as expected         */
  35. That isn't going to work too well for negative numbers, is it?
  36.  
  37.     double round(x)
  38.         double x;
  39.         {
  40.         return x < 0 ? -floor(0.5-x) : floor(0.5+x);
  41.         }
  42.  
  43. is closer.  
  44.