我试图制作一个计算平方根的递归代码。
我需要测试我的猜测(difference between x and guess*guess)
。
如果猜测不够准确,你需要再次猜测。
新猜测应为= 0.5 * (lastGuess + x / lastGuess)
。
如何将用户输入分配到x
,然后将x
发送到squareRoot方法以计算平方根?
另外,我想我需要一个while循环来继续猜测,直到答案足够接近?
这就是我现在所拥有的:
import java.util.Scanner;
public class Recursive
{
public static void main(String []args)
{
Scanner keyboard = new Scanner(System.in);
double x;
double error;
System.out.println("Enter a number that you want the square root of");
x = keyboard.nextDouble();
double guess = x / 2;
System.out.println("Enter an acceptable error");
error = keyboard.nextDouble();
System.out.println("The square root of " + x + " is " + squareRoot(x, guess, error));
}
public static double squareRoot(double x, double guess, double error)
{
double newGuess;
if(Math.abs(guess * guess - x) <= error)
{
return guess;
}
else
{
newGuess = 0.5 * (guess + (x / guess));
return newGuess;
}
}
}