I might have a noob question here, but searching the site hasn't yelded anything. I'm learning to program in C and I'm trying to build a function from scratch that rounds floats to the nearest integer, without using math.h. Here's my code:
void main()
{
float b;
for(b = 0; b <= 2; b = b + 0.1)
{
printf("%f ", b);
printf("%i ", (int)b);
printf("%f ", b - (int)b);
printf("Nearest: ");
if((b - (int)b)<0.5)
printf("%i ", (int)b);
else
printf("%i ", (int)b + 1);
printf("Function: %i ", round_near(b));
printf("\n");
}
getchar();
}
int round_near(float b)
{
if((b - (int)b)<0.5)
return(int)b;
else
return (int)b + 1;
}
My results looks like this:
Some of the code is superfluous and was just meant to see some of the individual steps of my function. What gives? Are there some shenanigans with float type variables I'm not aware of?