home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ferkel.ucsb.edu!taco!rock!stanford.edu!ames!haven.umd.edu!darwin.sura.net!zaphod.mps.ohio-state.edu!caen!batcomputer!munnari.oz.au!goanna!ok
- From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe)
- Newsgroups: comp.lang.c
- Subject: Re: Rounding floats to integers
- Message-ID: <15905@goanna.cs.rmit.oz.au>
- Date: 12 Nov 92 03:44:26 GMT
- References: <92314.134711IA8@psuvm.psu.edu>
- Organization: Comp Sci, RMIT, Melbourne, Australia
- Lines: 33
-
- In article <92314.134711IA8@psuvm.psu.edu>, IA8@psuvm.psu.edu (Alan R. Heyd) writes:
- > Is there a C routine that will round off floating point numbers
- > to the nearest integer.
-
- C directly supports three ways of converting a float to an integer:
-
- #include <math.h>
- int i;
- double x;
-
- i = x; /* truncate */
- i = floor(x); /* floor */
- i = ceil(x); /* ceiling */
-
- Note that in the latter two, TWO conversions are involved: double ->
- integer in double format -> integer.
-
- C does _not_ include a round-to-nearest integer function. Many
- implementations have one, but the names vary. rint() is one of those names.
-
- > What I do now is add 0.5 to the float before it is converted to
- > an integer, for example:
- > i = 6.0 / 0.3; /* i = 19 */
- > i = 6.0 / 0.3 + 0.5; /* i = 20 as expected */
- That isn't going to work too well for negative numbers, is it?
-
- double round(x)
- double x;
- {
- return x < 0 ? -floor(0.5-x) : floor(0.5+x);
- }
-
- is closer.
-