您的程序有未定義的行爲,因爲在您輸入循環時,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;
}
但大部分的變量不會被初始化或使用??? –
我知道那就是爲什麼我輸了。我應該讓old_guess = n/2? – billnye852
在scanf之後,把這個:'old_guess = n/2;' –