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 ("%f\n", (float)root);
}while (1);
return 0;
}
所以如果我计算 2000 的平方根,它应该返回 2(1.414..) 的平方根,但它只给出一个近似值:1.50000 如何使用整数纠正这个问题并用浮点数转换它们?谢谢
解决方案
x = (x + a / x) / 2
fora = 2000000
和x0 = 1000
(所有整数变量)的迭代是1500
,1416
和1414
. 然后200000000
给14142
等等。
推荐阅读
- php - 是否可以在长时间运行的 PHP 进程中捕获/处理/检测系统时间何时更改?
- multilevel-analysis - 使用 hmi 和鼠标输入二进制缺失数据——错误:C 堆栈使用 7969776 太接近限制
- c++11 - 在 boost:heap 上使用 lambda 函数时的 bad_function_call
- r - id 变量在另一个 id 变量中按顺序排列
- ruby-on-rails - 等效于 .where 在 before_save 中没有查询 - Rails
- dask - 使用 map_blocks 根据每个块的内容计算一个堆
- r - 合并/合并颜色并将图例填充为一个
- java - 遍历从 OpenCSV 生成的 Map
- python - Python:类中的字典理解
- c++ - 媒体上的 libavcodec 完全在内存中