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