实现sqrt()函数

 求一个正数N的开方, 并且可以指定精度, 要求不能用库函数sqrt

方法一:如下所示,先求sqrt(N)的整数部分,再求小数点后1位,2位 ... ...

方法二:牛顿迭代法,根据公式 Ai+1 = (Ai+number/Ai)/2 ,其中Ai 的初始值,即A1任取,如1,2,3 ...

// 求一个正数N的开方, 并且可以指定精度, 要求不能用库函数sqrt

#include <stdio.h>
#include <stdlib.h>

double my_sqrt2(double number, int point)
{
    double new_guess;
    double last_guess;

    if (number < 0) {
        printf("Cannot compute the square root of a negative number!\n");
        return -1;
    }

    printf("Method 2:\n");
    new_guess = 1;
    do {
        last_guess = new_guess;
        new_guess = (last_guess + number/last_guess) / 2;
        printf("%.*lf\n", point, new_guess);
    } while (new_guess != last_guess);

    return new_guess;
}

double my_sqrt1(double n, int point)
{
    if (n < 0) {
        printf("Cannot compute the square root of a negative number!\n");
        return -1;
    }

    int i,j;
    for( i=1; i-n<0; i++ ) // 求得i的开方的整数部分
        if( i*i-n > 0 )
            break;

    double answer = i-1;
    double incr = 0.1;
    for( j=1; j<=point; j++) // 第j次循环,求得i的开方的小数部分的第j位
    {
        for( i=1; i<10; i++ )
        {
            answer += incr;
            if( answer*answer-n > 0 )
                break;
        }
        answer -= incr;
        incr /= 10;
    }
    incr *= 10;
    printf("Method 1:\n");
    printf("sqrt(%lf) is between %.*lf - %.*lf\n", n, point, answer, point, answer+incr);
    return answer;
}

int main(void)
{
    int point;
    double n;
    printf("请输入正整数N: ");
    scanf("%lf",&n);
    printf("请输入精确到小数点后的位数: ");
    scanf("%d",&point);

    my_sqrt1(n,point);
    my_sqrt2(n,point);

    return 0;
}

 

posted on 2014-07-27 13:47  DayByDay  阅读(492)  评论(0编辑  收藏  举报