c++ - Wrong answer while calculating the nth root of number in cpp -
i calculating n'th root of positive integer using standard library method pow() .here snippet program :
double x,y; x=pow(64,(1.0/3)); int z; printf("x=%lf\n",x); z=(int)x; printf("%d\n",z);
but while finding cube root of 64. x printed 4.000000 while z 3. why ?
can suggest better algorithm , same ?
if print more digits on x
, you'll see problem (i chose 30 randomly):
double x ; x = pow(64, 1.0/3); printf("x=%.30lf\n",x);
output:
x=3.99999999...999600000000
so obvisouly, if cast x
int
became 3
.
there not 'perfect' solution. if you're dealing integer, create own root function, if want able use float, you'need deal accuracy problem due floating point representation.
there maybe c libraries kind of problems.
Comments
Post a Comment