开发者

How to find square root of a number using a recursive function? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasona开发者_运维问答bly answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 9 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜