2013-11-15 25 views
2

我在寫一個解決平方根的程序。該程序似乎正常工作,直到它到達while ((x1-x2)>dif)循環,然後永遠運行,返回最後的x2。 感謝您的閱讀!爲什麼我的java程序連續運行並沒有完成主要方法?

import java.util.Scanner; 
public class lab13 { 
static double getSqrt(double s) { 
    double dif = .000001; 
    double S = 0; 
    if (s == 0) 
     return 0; 
    double a = s; 
    int n = 0; 
    if (a >= 100) { 
     while (a >= 100) { 
      a /= 100; 
      n++; 
     } 
    } 
    else { 
     while (a < 1) { 
      a *= 100; 
      n --; 
     } 
    } 
    System.out.println(a + " " + n); 

    if (a < 10) { 
     S = 2*Math.pow(10, n); 
    } 
    else { 
     S = 6*Math.pow(10, n); 
    } 
    System.out.println(S); 

    double x1, x2; 
    x1=S; 
    System.out.println(x1); 
    x2 = (0.5)*(x1+(s/x1)); 
    System.out.println(x2); 

    while ((x1-x2)>dif) { 
     x2 = (0.5)*(x1+(s/x1)); 
    } 
    System.out.println(x2); 
    return x2; 
} 

public static void main(String[] args) { 
    Scanner in = new Scanner (System.in); 

    System.out.print("Enter n (negative to stop):"); 
    double n = in.nextDouble(); 
    while (n >= 0) { 
     System.out.println(getSqrt(n)); 
     System.out.println();Math.sqrt(n); 

     System.out.print("Enter n(negative to stop):"); 
     n = in.nextDouble(); 

     System.out.println(getSqrt(n)); 
    } 
    } 
} 

回答

2

注意你在做什麼。

x2 = (0.5)*(x1+(s/x1)); 

該表達式的右側在循環內部是常量,所以x2的值永遠不會改變。

2
while ((x1-x2)>dif) { 
    x2 = (0.5)*(x1+(s/x1)); 
} 

麻煩的是,x2被更新,但x1不是。對於Newton's method要工作x1需要先前的猜測,但由於它沒有更新x1永遠是第一次猜測

while ((x1-x2)>dif) { 
    double prev = x2; 

    x2 = (0.5)*(x1+(s/x1)); 
    x1 = prev; 
} 
1
while ((x1-x2)>dif) { 
    x2 = (0.5)*(x1+(s/x1)); 
} 

無論x1也不dif也不s不要在裏面while改變。 x2從原始值發生變化,但其值在每次迭代中設置爲相同值(因爲它僅取決於x1s)。因此,循環只運行一次,否則它將永遠運行。

你爲什麼期望這不會失敗?因爲

+0

HA的!很高興你添加了最後的評論。我只是喜歡諷刺意見。 – ToonLink

1

那是在你的代碼

while ((x1-x2)>dif) { 
    x2 = (0.5)*(x1+(s/x1)); 
} 

X2永遠不會增加,不會改變它的值,x1-x2保持不變,> DIFF,所以你永遠不會退出圈外

相關問題