2017-02-20 32 views
-1

我必須編寫一個程序,該程序將使用while循環找到平方根。我被給了這個new_guess = (old_guess + (n/old_guess))/2.0;但我不完全理解,用它做,這是我所:如何使用while語句來查找使用while循環的平方根

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。我知道它確實是錯的,但我真的不知道如何開始,因爲當我輸入一個數字時,它就立即停止。

+1

但大部分的變量不會被初始化或使用??? –

+0

我知道那就是爲什麼我輸了。我應該讓old_guess = n/2? – billnye852

+0

在scanf之後,把這個:'old_guess = n/2;' –

回答

1

您的程序有未定義的行爲,因爲在您輸入循環時,new_guessold_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; 
}