PC Safe
PC Safe

Reputation: 25

Representation of a pow function in the form of a loop

Hello I need help solving this task, if anyone had a similar problem it would help me a lot.

I made a program that calculates the nth root of a number. Here's code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define EPS 1e-5
/*
*/
int main()
{
double xs,xn,n,x,degree=1,l;
printf("Enter n>0:");
scanf("%lf",&n);
while(n<1)
{
    printf("Enter n>0:");
    scanf("%lf",&n);
}
printf("Enter x:");
scanf("%lf",&x);
xn=(x+1)/n;

while(fabs(xn-xs)>EPS)
{
    xs=xn;
    l=pow(xs,n-1);
    xn=(1/n)*((n-1)*xs+(x/l));
}
printf("%lf",xn);
return 0;
}

I wanted to modify this program, ie. not to use the pow function.I wanted to use the loop for what the pow function was doing. This is a modification code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define EPS 1e-5
 /*
 */
int main()
{
double xs,xn,n,x,degree=1;
printf("Enter n>0:");
scanf("%lf",&n);
while(n<1)
{
    printf("Enter n>0:");
    scanf("%lf",&n);
}
printf("Enter x:");
scanf("%lf",&x);
xn=(x+1)/n;

while(fabs(xn-xs)>EPS)
{
    xs=xn;
    for(int i=1;i<=(n-1);i++)
    {
        degree=degree*xs;
    }
    xn=(1/n)*((n-1)*xs+(x/degree));
}
printf("%lf",xn);

return 0;
}

But I do not get the same result in both codes, ie. in the first code I get the correct result, while in the second I don't.Also, I don't understand what the problem is in the second code?

Upvotes: 0

Views: 50

Answers (1)

dbush
dbush

Reputation: 224082

Your for loop that calculates the power sits inside another loop, so on the next iteration of the outer loop degree still has the same value it had prior. You need to reset it before entering the inner loop:

degree=1;
for(int i=1;i<=(n-1);i++)
{
    degree=degree*xs;
}

Upvotes: 0

Related Questions