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

  1. Path: sparky!uunet!stanford.edu!ames!elroy.jpl.nasa.gov!nntp-server.caltech.edu!roder
  2. From: roder@cco.caltech.edu (Brenda J. Roder)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Rounding floats to integers
  5. Date: 10 Nov 1992 17:40:27 GMT
  6. Organization: California Institute of Technology, Pasadena
  7. Lines: 31
  8. Message-ID: <1dos6bINN3jh@gap.caltech.edu>
  9. References: <1dn37oINNr42@uwm.edu>
  10. NNTP-Posting-Host: sandman.caltech.edu
  11.  
  12. eli@csd4.csd.uwm.edu (Elihu Lubkin) writes:
  13.  
  14. >From: IA8@psuvm.psu.edu (Alan R. Heyd)
  15.  
  16. [How to round floats?]
  17. >>What I do now is add 0.5 to the float before it is converted to
  18. >>an integer, for example:
  19. >>
  20. >>          int i;
  21. >>                                 /* Using Turbo C on and IBM PC: */
  22. >>          i = 6.0 / 0.3;         /*   i = 19                     */
  23. >>          i = 6.0 / 0.3 + 0.5;   /*   i = 20 as expected         */
  24. >>
  25.  
  26. >      But if i = -6.0 / 0.3 + 0.5 then i = -19 so you also have to
  27. >watch out for the sign.
  28. >                          Thelma Lubkin
  29.  
  30. Yes, so use floor (in math library) instead of depending on the truncation.
  31. i.e.
  32.  
  33.     i = floor(-6.0 / 0.3 + 0.5);  /* i = -20 as expected */
  34. this equation will work for both signs (since it does an explicit truncation
  35. in a defined direction).
  36.  
  37.  
  38.  
  39. -- 
  40. -- Brenda (roder@cobalt.caltech.edu)
  41. Thought before action, if there's time.
  42.     _The Edge_  Dick Francis
  43.