I know that C++ provides us with a ceil function. For practice, I was wondering how can we implement the ceil function in C++. The signature of the method is public static
The previous code recommendation:
int ceil(float val)
{
int temp = val * 10;
if(val%10)
return (temp+1);
else
return temp;
}
does not compile: Receives "error C2296: '%': illegal, left operand has type 'float'" on line 4 "if(val%10)" because you can't use the mod operator (%) on a float or double. See: Why we can't use operator % for float and double type operands? It also does not work for decimal values whose precision is not greater than 1/10.
Whereas, the prior code recommendation:
int ma_ceil(float num)
{ int a = num;
if ((float)a != num)
return num+1;
return num;
}
works well, as long as you don't go beyond the bounds of a floating point value. num = 555555555; or num = -5.000000001 are not going to work unless you use a double.
Also, because floats and doubles are stored in IEEE floating point format, the binary representations stored can be inexact. For, instance:
float num = 5; in some instances might not get the value 5.0000000 assigned, but rather 5.9999998 or 5.00000001. To correct the prior code version, I'd recommended changing the return value to use integer math rather than relying on the accuracy of the floating point value, as follows:
int ma_ceil(float num)
{ int a = num;
if ((float)a != num)
return a+1;
return a;
}