我在寫一個解決平方根的程序。該程序似乎正常工作,直到它到達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));
}
}
}
HA的!很高興你添加了最後的評論。我只是喜歡諷刺意見。 – ToonLink