I am trying to write a C code of a function that takes an integer from 0
to 125
and return the cubic root of that integer only if it's a whole number ( 1,2,3,4,5 ) and if it's not, return 0
instead. So I wrote this code:
unsigned int cubic(unsigned int n) {
if (n > 125)
return 0;
double root = pow(n, (1 / 3.));
double rem = (double)(roundf(root)) - root;
if (rem != 0)
return 0;
else
return roundf(root);
}
this function works fine with all cases except for the number 64
and 125
.
in these cases it returns 0
instead of the cubic roots of these numbers which are 4
and 5
respectively.
Can anybody explain to me why this is happening?
Because
1 / 3.
cannot accurately represented as a floating point number, the floating point calculationpow(64, (1 / 3.))
might produce a number very close to4
, but a tiny bit smaller or larger, different enough from4
for(double)(roundf(root)) - root
to be different from0
.You could work around this precision issue this way:
Instead of
pow(n, 1 / 3.)
, you could usecbrt(n)
if available on your system, but the precision issue might still be present.For your goal, it seems much simpler to iterate over the possible integer roots and check:
Or even more explicit: