How to calculate the n-th root of a number in C?

Asked

Viewed 1,207 times

3

I tried to figure it out, only pow returns only the number 1 to me :

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

1 answer

2


Try it like this:

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

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, therefore it is necessary to return float or double otherwise there will be rounding.

2) How z is a whole and you were doing 1/z, this result will also be whole, since the constant 1 is treated as integer and C does not automatically promote the result of a integer split to float or double. If you passed, 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 high to zero is 1, so the constant result you were receiving. The solution is to use 1.0 instead of 1, what force the type of result to be double

  • Gave error:-> homesimulation02.c: At top level: homesimulation02.c:46:9: error: Conflicting types for ːfuncao1' double funcao1(int y,int z){

  • 1

    This is because you have not changed the prototype of the function. Go to the top of the file and change the return type of the prototype that is there as well.

  • continues showing only 1

  • #include<stdio. h> #include<stdlib. h> #include<Math. h> int main(){ int x=1; imprimemenu(); questao03(x); Return(0); } int imprimemenu(){ printf(" n(1) function 1 n"); printf(" n(2) function 2 n"); printf(" n(3) function 3 n"); printf(" n(0) exit n"); Return(0); Return(0); ;}

  • 1

    Here is working normally. See for yourself on this link.

  • has how you send me the whole code to calculate the n-th root and show the result

  • Hadn’t seen the link

  • I did the same root as you in my code and the calculated root is totally different from the correct one.Follow the code link: https://ideone.com/PUXuU

  • Your scanf and printf are using %i. Change to %d when reading integer and %lf when printing double.

  • In this same code my menu only closes when the user selects all functions, it should close when the user type 0

  • In this case I suggest that you open a new specific question for this case. It is already leaving the focus of the issue and it is difficult to follow.

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.