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:
1 2 3 4 5 6 7 8
// 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 ) ;