求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;
}
计算平方根的公式与程序代码

本文介绍了求正数平方根的数学公式,并提供了一个使用C语言实现的程序代码实例,展示了如何通过迭代逼近算法计算平方根。
2万+

被折叠的 条评论
为什么被折叠?



