How to calculate the nth root of a number in C?


I tried to calculate it like this, but pow only returns the number 1 for me:

int funcao1(int y,int z){
 int k;
 k = pow(y,1/z);


Try it like this:

double funcao1(int y,int z){
 double k;
 k = pow(y,1.0/z);

Or better yet:

double raiz(int radicando, int indice){
  return pow(radicando, 1.0/indice);

What has changed:

1) the root of a number can be fractional, so you must return float or double otherwise there will be rounding.

2) Since z is an integer and you were doing 1/z , this result will also be an integer, since the constant 1 is treated as an integer and C does not automatically promote the result of an integer division to float or double . If you were to pass, say 4 and 2, the function would raise 4 to 1/2, but 1/2 is zero when we convert to integer (rounding is down). Anything raised to zero is 1, hence the constant result you were getting. The solution is to use 1.0 instead of 1 , which forces the result type to be double

Scroll to Top