当前位置: 代码迷 >> 综合 >> C++sqrt()
  详细解决方案

C++sqrt()

热度:56   发布时间:2023-11-27 17:15:18.0
double sqrt(int x)
{
    //公式:a+b/(2a+b/(2a+b/(2a+b/...)))//找出aint a;for(a = 0;a * a <= x;a++);a--;//得到bint b = x - a * a;//如果b=0,说明a*a=x即x的平方根是aif(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类型的精度极限
}