標籤:
求一個正數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()函數