首页 > 解决方案 > 使用整数与牛顿求平方根

问题描述

在这个程序中,我试图用牛顿方程1/2(x+a/x) 仅使用整数来计算平方根。因此,如果我将这个等式至少重复 10 次,它应该将数字除以 1000,并给出 a/1000 的平方根的近似值。这是代码:

int main (){
    int32_t a, x;  //integers a and x
    float root;

     do{
    scanf ("%d", &a);   // get value of a from the user
    
    
    if (a < 1000 ){   // if chosen number is less than 1000 the programm ends.
    break;
    }
    
    x = ((float) a / 1000);   //starting value of x is a / 1000;
    for (int i = 0; i < 50;i++)
    {

        root = ((float) x * (float) x + a/1000) / ((float)2*x);  // convert int to float //through casting
        x = (float)root;    // refresh the value of x to be the root of the last value.


    }
    printf ("%f\n", (float)root);
     }while (1);

    return 0;

}

所以如果我计算 2000 的平方根,它应该返回 2(1.414..) 的平方根,但它只给出一个近似值:1.50000 如何使用整数纠正这个问题并用浮点数转换它们?谢谢

标签: cnumerical-methodsnewtons-methodsquare-root

解决方案


x = (x + a / x) / 2fora = 2000000x0 = 1000(所有整数变量)的迭代是1500,14161414. 然后20000000014142等等。


推荐阅读