我试图通过挤压定理使程序近似于数字的平方根。如果数字高于1(简单示例为100),则将间隔设置为[1,100],取中点,如果该数字的平方大于100,则更新为高并打印新间隔。如果它更低,它会更新为低,直到它们之间的空间在EPSILON内。我的问题是我似乎不能让它进入else语句以更新低。之前的所有输出都是正确的。它正确打印前五行然后终止而不更新低。
public static void main(String[] args) {
System.out.println("Enter a number to find its square root -> ");
Scanner cin = new Scanner(System.in);
double number = cin.nextDouble();
double low = 0;
double high = 0;
double midPoint;
double midPointSqr;
final double EPSILON = .000001;
if (number < 0)
System.out.printf("The square root of %f is NaN%n", number);
else if (number < 1) {
low = 0; high = 1;
}
else {
low = 1;
high = number;
midPoint = (low+high)/2;
midPointSqr = (midPoint*midPoint);
System.out.printf("[%.6f, %.6f]%n", low, high);
high = midPoint;
System.out.printf("[%.6f, %.6f]%n", low, high);
while ((Math.abs(midPoint*midPoint)-number) >= EPSILON) {
midPoint = (low+high)/2;
if (midPointSqr > number) {
high = midPoint;
System.out.printf("[%.6f, %.6f]%n", low, high);
midPoint = (low+high)/2;
midPointSqr = midPoint*midPoint;
}
else if (midPointSqr == number)
System.out.println("null");
else {
low = midPoint;
System.out.printf("[%.6f, %.6f]%n", low, high);
midPoint = (low+high)/2;
midPointSqr = midPoint*midPoint;
}
}
}
/*Output should look like this
1 Enter a number to find its square root -> 100
2 [1.000000 , 100.000000]
3 [1.000000 , 50.500000]
4 [1.000000 , 25.750000]
5 [1.000000 , 13.375000]
6 [7.187500 , 13.375000]
7 [7.187500 , 10.281250]
8 [8.734375 , 10.281250]
9 [9.507813 , 10.281250]
10 [9.894531 , 10.281250]
11 [9.894531 , 10.087891]
12 [9.991211 , 10.087891]
13 [9.991211 , 10.039551]
14 [9.991211 , 10.015381]
15 [9.991211 , 10.003296]
16 [9.997253 , 10.003296]
17 [9.997253 , 10.000275]
18 [9.998764 , 10.000275]
19 [9.999519 , 10.000275]
20 [9.999897 , 10.000275]
21 [9.999897 , 10.000086]
22 [9.999991 , 10.000086]
23 [9.999991 , 10.000039]
24 [9.999991 , 10.000015]
25 [9.999991 , 10.000003]
26 [9.999997 , 10.000003]
27 [9.999997 , 10.000000]
28 [9.999999 , 10.000000]
29 [10.000000 , 10.000000]
*/
答案 0 :(得分:2)
以下是我清理过的代码版本:
public static double approximateSqrt(double number) {
double low = 0;
double high = 0;
double midPoint;
double midPointSqr;
final double EPSILON = .000001;
if (number < 0) {
System.out.printf("The square root of %f is NaN%n", number);
return Double.NaN;
} else if (number < 1) {
low = 0;
high = 1;
} else {
low = 1;
high = number;
}
midPoint = (low + high) / 2;
midPointSqr = (midPoint * midPoint);
while (Math.abs(midPointSqr - number) >= EPSILON) {
System.out.printf("[%.6f, %.6f]%n", low, high);
if (midPointSqr > number) {
high = midPoint;
} else {
low = midPoint;
}
midPoint = (low + high) / 2;
midPointSqr = (midPoint * midPoint);
}
System.out.printf("Final. midpoint=%.6f num=%.6f%n", midPoint, number);
return midPoint;
}
public static void main(String[] args) {
System.out.println("Enter a number to find its square root -> ");
Scanner cin = new Scanner(System.in);
double number = cin.nextDouble();
approximateSqrt(number);
}