簡體   English   中英

為什么我的java程序連續運行並且沒有完成main方法?

[英]Why is my java program continuously running and not finishing the main method?

我正在寫一個解決平方根的程序。 該程序似乎可以正常運行,直到到達while ((x1-x2)>dif)循環,然后永遠運行,而不會返回最終的x2 謝謝閱讀!

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));
    }
  }
}

注意您在做什么。

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

該表達式的右側在循環內是常量,因此x2的值永遠不變。

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

問題是x2正在更新,而x1沒有更新。 為了使牛頓方法有效, x1必須是先前的猜測,但由於x1尚未更新,因此永遠是第一個猜測

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

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

x1difs都不會在while內改變。 x2從原始值更改,但是在每次迭代中將其值設置為相同的值(因為它僅取決於x1s )。 因此,要么循環僅運行一次,要么將永遠運行。

您為什么期望這不會失敗?

那是因為在您的代碼中

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

x2從不增加,從不更改其值, x1-x2保持不變且> diff,因此您永遠不會退出循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM