home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16325 < prev    next >
Encoding:
Text File  |  1992-11-11  |  1.6 KB  |  44 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!pipex!warwick!coventry!champion
  3. From: champion@cch.coventry.ac.uk (Alun)
  4. Subject: Re: Rounding floats to integers
  5. Message-ID: <BxJx0s.6q8@cck.coventry.ac.uk>
  6. Sender: news@cck.coventry.ac.uk (news user)
  7. Nntp-Posting-Host: cc_sysh
  8. Organization: Coventry University, Coventry, UK.
  9. References: <92314.134711IA8@psuvm.psu.edu> <rfries.123@sceng.ub.com>
  10. Date: Wed, 11 Nov 1992 12:22:03 GMT
  11. Lines: 31
  12.  
  13. In article <rfries.123@sceng.ub.com> rfries@sceng.ub.com (Robert Fries) writes:
  14. ~In article <92314.134711IA8@psuvm.psu.edu> IA8@psuvm.psu.edu (Alan R. Heyd) writes:
  15. ~
  16. ~>What I do now is add 0.5 to the float before it is converted to
  17. ~>an integer, for example:
  18. ~
  19. ~To round to NEAREST integer, you'd have to test if fractional part is less 
  20. ~than 0.5; if YES, drop fractional part, if NO, add 0.5, then drop fraction.
  21. ~You'd also get to choose what to do if fractional part is EXACTLY 0.5.
  22.  
  23. No !! If you add 0.5 to something with a fractional part of less than 0.5
  24. you will still have the same "int" value.
  25. But adding 0.5 is not general enough..
  26.  
  27. int round(float n)
  28. {
  29.     if(n < 0)
  30.         return (int)(n - 0.5);    
  31.     return (int)(n + 0.5);     // Doesn't the function do the cast automatically
  32. }
  33.  
  34. I prefer this than using the math libraries where you have to test
  35. if the fraction is greater or lesser than 0.5 then use ceil() or floor()
  36. respectively. Not only that they return doubles so internal conversion
  37. has to be done anyway.
  38.  
  39.     -Alun
  40.     
  41. -- 
  42. A.Champion                |  That's an interesting point, in the sense of
  43. (champion@uk.ac.cov.cck)  |    being very not interesting at all. - The Liar
  44.