home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / c / 16582 < prev    next >
Encoding:
Internet Message Format  |  1992-11-15  |  1.7 KB

  1. Path: sparky!uunet!decwrl!waikato.ac.nz!comp.vuw.ac.nz!amigans!acheron!alien
  2. Newsgroups: comp.lang.c
  3. Subject: Re:  Rounding floats to integers
  4. Message-ID: <alien.0144@acheron.amigans.gen.nz>
  5. From: alien@acheron.amigans.gen.nz (Ross Smith)
  6. Date: 16 Nov 92 08:28:42 GMT+12
  7. References: <alien.010i@acheron.amigans.gen.nz> <1e3brhINN3eb@uwm.edu>
  8. Distribution: world
  9. Organization: Wanganui Amigans, Wanganui, NZ
  10. Lines: 40
  11.  
  12. In article <1e3brhINN3eb@uwm.edu> eli@csd4.csd.uwm.edu (Elihu Lubkin) writes:
  13. >alien@acheron.amigans.gen.nz (Ross Smith) writes:
  14. >:
  15. >: In programs that have to do this sort of calculation, I usually stick in
  16. >: a macro like this :
  17. >:
  18. >:    #define round(x) ((int)floor((x)+0.5))
  19. >:
  20. >: This handles negative numbers correctly, e.g.
  21. >:
  22. >:    i = round(5.0/0.4);   /* yields 13 (correct)       */
  23. >:    i = round(-5.0/0.4);  /* yields -12 (also correct) */
  24. >:
  25. >: (5/0.4 = 12.5, and the standard convention is that halves are rounded up,
  26. >: so 12.5 gives 13, -12.5 gives -12.)
  27. >:
  28. >     and round(-12.99999...)  /* yields -12 (correct?)  */
  29. >               interesting convention.
  30. >                                --Thelma Lubkin
  31.  
  32. No, it yields -13. Work it out...
  33.  
  34. round (-12.99999) -> ((int)floor((-12.99999)+0.5))
  35.                   -> ((int)floor(-12.49999))
  36.                   -> ((int)-13.0)
  37.                   -> -13
  38.  
  39. The floor() function is required by the standard to yield the greatest integer
  40. less than or equal to its argument.
  41.  
  42. floor(12.34) -> 12.0
  43. floor(-12.34) -> -13.0
  44.  
  45. --
  46. ...... Ross Smith (Wanganui, NZ) ...... alien@acheron.amigans.gen.nz ......
  47.    "Let us leave this festering hellhole.  Let us think the unthinkable,
  48. let us do the undoable.  Let us prepare to grapple with the ineffable
  49. itself, and see if we may not eff it after all." (Dirk Gently)
  50. --
  51.  
  52.