How to find square root of a number using a recursive function? [closed]
Basically i want to create a recursive function to implement this program in C
#include <stdio.h>
main()
{
float guess=1,num,num1;
int i;
printf("enter any number:\n");
scanf("%f",&num);
num1=num;
for (i=1;num1>1;i++,num1/=10); //to calculate no of digits in input
i=i/2;
printf("i:%d\n",i); //to make a better guess
for (;i>0;i--,guess*=10);
printf("guess = %f\n",guess);
for (i=1;i<=10;i++) //evaluate square root improving accuracy with each loop
{
guess=(guess+num/guess)/2;
}
printf("sqrt: %f\n",guess);
}
Something like this:
#include <math.h>
#include <float.h>
float MySqrt(float num, float prev)
{
float next = (prev+num/prev)/2;
if (fabs(next-prev)<FLT_EPSILON*next)
return next;
return MySqrt(num, next);
}
To call it, pass 1.0
as your initial guess for the prev
parameter.
You can easily make this fail with a stack overflow by passing in bad data, but you probably aren't going to be tested on that in this assignment.
精彩评论