實現sqrt()函數

來源:互聯網
上載者:User

標籤:

 求一個正數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;}

 

實現sqrt()函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.