c -用牛顿整数求平方根



在这个程序中,我试图用整数计算牛顿方程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 ("%fn", (float)root);
}while (1);
return 0;
}

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

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char * *argv, char * *envp) {
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 program ends.
break;
}
x = (int32_t)((float) a / 1000.0f);   //starting value of x is a / 1000;
for (int i = 0; i < 1000; i++) {
// Fixed formula based on (x+a/x)/2
root = ((float)x + (((float)a) / (float)x)) / 2.0f;
//Below, wrong old formula
//root = ((float) x * (float) x + a / 1000) / ((float) 2 * x);  // convert int to float //through casting
x = (int32_t) root;    // refresh the value of x to be the root of the last value.
}
printf ("%fn", root);
} while (1);

return (EXIT_SUCCESS);
}

相关内容

  • 没有找到相关文章

最新更新