[英]Why is this recursive method on guessing the square root of a user inputted number not working
For some reason I keep just getting error trying to compile this code, but it seems tat everything works, right?出于某种原因,我在尝试编译此代码时不断出错,但似乎一切正常,对吧?
import java.util.*;导入 java.util.*; public class squareRoot { public static void input(){
公共 class squareRoot { 公共 static 无效输入(){
Scanner input = new Scanner (System.in);
double number = 16;
double root;
root = square(number);
System.out.println("Enter Guess");
double oldguess = input.nextDouble();
squareRoot(0, oldguess);
}
public static double square(double number){
double t;
double squareroot = number / 2;
do {
t = squareroot;
squareroot = (t + (number / t)) / 2;
} while ((t - squareroot) != 0);
return squareroot;}
public static double squareRoot(double newguess, double oldguess){
if (newguess == square(19)){
return newguess;
}
else{
newguess = (oldguess + (19/oldguess))/2;
System.out.println(newguess);
return squareRoot(newguess, oldguess);
}
}
}
Because oldguess
is a constant.因为
oldguess
是一个常数。 So after the first run through, this code produces the same result every time:所以在第一次运行之后,这段代码每次都会产生相同的结果:
newguess = (oldguess + (19/oldguess))/2;
You need to cache the newguess
at the start of the else
, do your calculation and then replace oldguess
with the cached value from newguess
.您需要在
else
的开头缓存newguess
,进行计算,然后将newguess
替换oldguess
中的缓存值。
Like so:像这样:
public static double squareRoot(double newguess, double oldguess) {
double cache;
if (newguess == square(19)) {
return newguess;
} else {
cache = newguess;
newguess = (oldguess + (19 / oldguess)) / 2;
oldguess = cache;
System.out.println(newguess);
return squareRoot(newguess, oldguess);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.