home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!decwrl!waikato.ac.nz!comp.vuw.ac.nz!amigans!acheron!alien
- Newsgroups: comp.lang.c
- Subject: Re: Rounding floats to integers
- Message-ID: <alien.0144@acheron.amigans.gen.nz>
- From: alien@acheron.amigans.gen.nz (Ross Smith)
- Date: 16 Nov 92 08:28:42 GMT+12
- References: <alien.010i@acheron.amigans.gen.nz> <1e3brhINN3eb@uwm.edu>
- Distribution: world
- Organization: Wanganui Amigans, Wanganui, NZ
- Lines: 40
-
- In article <1e3brhINN3eb@uwm.edu> eli@csd4.csd.uwm.edu (Elihu Lubkin) writes:
- >alien@acheron.amigans.gen.nz (Ross Smith) writes:
- >:
- >: In programs that have to do this sort of calculation, I usually stick in
- >: a macro like this :
- >:
- >: #define round(x) ((int)floor((x)+0.5))
- >:
- >: This handles negative numbers correctly, e.g.
- >:
- >: i = round(5.0/0.4); /* yields 13 (correct) */
- >: i = round(-5.0/0.4); /* yields -12 (also correct) */
- >:
- >: (5/0.4 = 12.5, and the standard convention is that halves are rounded up,
- >: so 12.5 gives 13, -12.5 gives -12.)
- >:
- > and round(-12.99999...) /* yields -12 (correct?) */
- > interesting convention.
- > --Thelma Lubkin
-
- No, it yields -13. Work it out...
-
- round (-12.99999) -> ((int)floor((-12.99999)+0.5))
- -> ((int)floor(-12.49999))
- -> ((int)-13.0)
- -> -13
-
- The floor() function is required by the standard to yield the greatest integer
- less than or equal to its argument.
-
- floor(12.34) -> 12.0
- floor(-12.34) -> -13.0
-
- --
- ...... Ross Smith (Wanganui, NZ) ...... alien@acheron.amigans.gen.nz ......
- "Let us leave this festering hellhole. Let us think the unthinkable,
- let us do the undoable. Let us prepare to grapple with the ineffable
- itself, and see if we may not eff it after all." (Dirk Gently)
- --
-
-