double sqrt(int x)
{
//公式:a+b/(2a+b/(2a+b/(2a+b/...)))
//找出a
int a;
for(a = 0;a * a <= x;a++);
a--;
//得到b
int b = x - a * a;
//如果b=0,说明a*a=x即x的平方根是a
if(b == 0)
{
return a;
}
//代入公式,其实可以无线拓展,但是我觉得精度够了
double m1 = 2 * a + b / (2 * a);//新的,相当于第17行里的m2
/*double m2 = 2 * a + b / m1;
double m3 = 2 * a + b / m2;
double m4 = 2 * a + b / m3;
double m5 = 2 * a + b / m4;
double m6 = 2 * a + b / m5;
double m7 = 2 * a + b / m6;
double m8 = 2 * a + b / m7;
double m9 = 2 * a + b / m8;
double m0 = 2 * a + b / m9;*/
double m0;//旧的,相当于第17行里的m1;
int i;
for(m0 = m1,i = 0;i < 10/*精度*/;m0 = m1/*一定要记得更新新旧*/,i++)
m1 = 2 * a + b / m0;//公式
double result = a + b / m1;//非重复部分
return result;//建议取前三位,第四位可能不准,毕竟到了double类型的精度极限
}
09-24
03-22
2126