Click to See Complete Forum and Search --> : newbie C question: rounding floats


klamath
11-13-2000, 10:37 PM
I guess it's time for me to admit my embarrassingly poor knowledge of C. Unfortunately, I need to use it for a few simple programming contest questions.

I want to convert a float into an int. C's normal type conversion seems to just chop off the decimal part of the float. I want to round properly (with 0.5 -> 1). How would one do this?

Also, I vaguely remember a way to switch the values on 2 variables without using a temp variable (using bit arithmetic). Can someone tell me how to do this?

------------------
- Klamath
Get my GnuPG Key Here (http://klamath.dyndns.org/mykey.asc)
Looking for an open source project to contribute to? Check out the BBB (http://bbb.sourceforge.net)

kmj
11-13-2000, 10:54 PM
To round a float, just add .5 then cast it to an int.

klamath
11-13-2000, 10:59 PM
Oh, and I rememberd the int swapping trick. This should work:

A^=B^=A^=B;

Swaps the values of A and B.

------------------
- Klamath
Get my GnuPG Key Here (http://klamath.dyndns.org/mykey.asc)
Looking for an open source project to contribute to? Check out the BBB (http://bbb.sourceforge.net)

klamath
11-13-2000, 11:16 PM
Another question - how do I tell if a given float has any digits past the decimal point?

i.e.
10.0000
versus
10.0001

I'd use (f % 1 == 0) , but gcc complains: apparently you can only use that on integers.

------------------
- Klamath
Get my GnuPG Key Here (http://klamath.dyndns.org/mykey.asc)
Looking for an open source project to contribute to? Check out the BBB (http://bbb.sourceforge.net)

siqe
11-14-2000, 12:06 AM
you can round by adding 0.5 and floor() ing the number. to tell if it has a decimal portion do this:

if( (number - floor(number)) > 0.0f )

it has a decimal portion.

siqe
11-14-2000, 12:07 AM
p.s. floor() is in the math.h

kmj
11-14-2000, 12:08 AM
how about casting it to an int, then comparing it as a float to istelf.
if (((float)((int)x)) == x) {x has no fractional part}

siqe
11-14-2000, 12:10 AM
p.p.s. i just looked in the math.h and its floor(double x); but i think it will work for you anyway. there might be a floorf(float x) for gcc, it depends.