我必须编写一个程序,使用while
循环找到平方根。我得到了这个new_guess = (old_guess + (n / old_guess)) / 2.0
;但我不完全明白该怎么做,这就是我所拥有的:
int main(void)
{
double n, x, new_guess, old_guess, value;
printf("Enter a number:");
scanf("%lf", &n);
x = 1.00000;
while (new_guess >= n) {
new_guess = (old_guess + (n / old_guess)) / 2.0;
printf("%10.5lf\n", fabs(new_guess));
}
return 0;
}
x
是最初的猜测。我真的迷失了如何做到这一点。这也是C.我知道它真的错了,但我真的不明白如何让它开始,因为当我输入一个数字时它就会马上停止。
答案 0 :(得分:1)
您的程序有未定义的行为,因为当您进入循环时,new_guess
和old_guess
都未初始化。
条件也不正确:您应该在new_guess == old_guess
时或在合理的最大迭代次数之后停止。
以下是修改后的版本:
#include <math.h>
#include <stdio.h>
int main(void) {
double n, x;
int i;
printf("Enter numbers:");
while (scanf("%lf", &n) == 1 && n >= 0.0) {
x = 1.0;
/* Using a while loop as per the assignment...
* a for loop would be much less error prone.
*/
i = 0;
while (i < 1024) {
double new_guess = (x + (n / x)) / 2.0;
if (new_guess == x)
break;
x = new_guess;
i++;
}
printf("%g: %.17g, %d iterations, diff=%.17g\n",
n, x, i, sqrt(n) - x);
}
return 0;
}
给定起始值,迭代次数随着n
的大小而增长,对于非常大的数字,超过500,但对于小数字,通常小于10。另请注意,此算法对n = 0.0
失败。
这是一个稍微复杂一点的方法,使用浮点分解并组合函数double frexp(double value, int *exp);
和double ldexp(double x, int exp);
。这些函数不执行任何计算,但允许更好的起点,在大多数值的4或5次迭代中完成:
#include <math.h>
#include <stdio.h>
int main(void) {
double n, x;
int i, exp;
printf("Enter a number:");
while (scanf("%lf", &n) == 1 && n >= 0.0) {
if (n == 0) {
x = 0.0;
i = 0;
} else {
frexp(n, &exp);
x = ldexp(1.0, exp / 2);
for (i = 0; i < 1024; i++) {
double new_guess = (x + (n / x)) / 2.0;
if (new_guess == x)
break;
x = new_guess;
}
}
printf("%g: %.17g, %d iterations, diff=%.17g\n",
n, x, i, sqrt(n) - x);
}
return 0;
}