float to int

closed account (j1AR92yv)
I had a question about a program. A program that takes an array of float (any size) and prints out the content to the nearest integer. However, the rounding has to be done by a function and not using a library.

The first function is
int round (float x)

and the second one is
void print_integers(float a [ ], int size)

For the first function it would round any float to the closest int, and return the int value, how does one go about this without actually using a library like c.math to round?
I suppose that you are not expected to take care of all the edge cases.
Something like this should suffice:

// round to nearest int. mid values are rounded away from zero
// invariant: result is within the range of int (undefined behaviour otherwise)
int round( float f )
    // note: computation done with double and truncated to int. for some values,
    //       this may be more accurate than f + ( f<0f ? -0.5f : +0.5f )
    return f + ( f<0 ? -0.5 : +0.5 ) ;
Registered users can post here. Sign in or register to post.