home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!stanford.edu!ames!elroy.jpl.nasa.gov!nntp-server.caltech.edu!roder
- From: roder@cco.caltech.edu (Brenda J. Roder)
- Newsgroups: comp.lang.c
- Subject: Re: Rounding floats to integers
- Date: 10 Nov 1992 17:40:27 GMT
- Organization: California Institute of Technology, Pasadena
- Lines: 31
- Message-ID: <1dos6bINN3jh@gap.caltech.edu>
- References: <1dn37oINNr42@uwm.edu>
- NNTP-Posting-Host: sandman.caltech.edu
-
- eli@csd4.csd.uwm.edu (Elihu Lubkin) writes:
-
- >From: IA8@psuvm.psu.edu (Alan R. Heyd)
-
- [How to round floats?]
- >>What I do now is add 0.5 to the float before it is converted to
- >>an integer, for example:
- >>
- >> int i;
- >> /* Using Turbo C on and IBM PC: */
- >> i = 6.0 / 0.3; /* i = 19 */
- >> i = 6.0 / 0.3 + 0.5; /* i = 20 as expected */
- >>
-
- > But if i = -6.0 / 0.3 + 0.5 then i = -19 so you also have to
- >watch out for the sign.
- > Thelma Lubkin
-
- Yes, so use floor (in math library) instead of depending on the truncation.
- i.e.
-
- i = floor(-6.0 / 0.3 + 0.5); /* i = -20 as expected */
- this equation will work for both signs (since it does an explicit truncation
- in a defined direction).
-
-
-
- --
- -- Brenda (roder@cobalt.caltech.edu)
- Thought before action, if there's time.
- _The Edge_ Dick Francis
-