求n的平方根
1 公式
正数n的平方根可以通过计算一系列近似值来获得,每个近似值都比前一个更加接近准确值,第一个近似值是1,接下来的近似值则通过下面的公式来获得:
ai+1=(ai+n/ai)/2
2 程序代码
#include<stdio.h> #include<stdlib.h> int main(int argc, char *argv[]) { float new_guess; float last_guess; float number; printf( "Enter a number: " ); scanf( "%f", &number ); if(number < 0) { printf( "cannot compute the square root of" "a negative number!\n" ); return EXIT_FAILURE; } new_guess = 1; do{ last_guess = new_guess; new_guess = ( last_guess + number / last_guess ) / 2; printf( "%.15e\n", new_guess ); }while( new_guess != last_guess ); printf( "square root of %g is %g\n", number, new_guess ); return EXIT_SUCCESS; }