You need to do something like this:
double sqrt(double S, double x, double n)
{
if (n == 0)
return x;
else
return sqrt(S,0.5*(x+S/x), n - 1);
}
S
will never change since its the number you want the square root of, while
x
will change. And you have to guess an initial x value to start with which cannot be zero, let us say 0.1, so the call can be like this:
x_n = sqrt(S, 0.1, 10);
If you think about it you are trying to find when
x^2 = S
, and we know that when
x = sqrt(S)
that
S/x = x
, whitch in turn means that
0.5*(x+S/x) = x
.