递归平方根查找器

时间:2017-11-12 20:00:03

标签: java

我遇到了一个试图找到数字平方根的方法的问题。 previousG是随机生成的数字。数字是平方根实际数字。我收到了堆栈溢出错误。我知道为什么因为我没有更新nextGuess变量。我想知道我应该在FindTheRoot方法中添加什么来阻止它。而且,我递归地做了这个。

public static void main(String[] args) {

        int srootArray[] = {9, 17, 25, 37, 49, 55, 999};

        Random randomGuess = new Random();

        for (int index = 0; index < srootArray.length; index++)
        {
            int previousGuess = randomGuess.nextInt(srootArray[index] + 1);
            System.out.println("Number: " + srootArray[index] + "... " + 
"First Guess: " + previousGuess);

            FindTheRoot(previousGuess, srootArray[index]);


            System.out.println("--------------------------------------------
------");
        }

    }

    public static double FindTheRoot(double previousG, int number)
    {
        double errorMargin = 0.00001;
        double nextGuess = (previousG + number / previousG) / 2;

        if (nextGuess < errorMargin)
            return nextGuess;
        else
        {
        System.out.printf("%S%.4f%n", "Next Guess: " , nextGuess);
        FindTheRoot(nextGuess, number);
    }

    return nextGuess;
}

}

1 个答案:

答案 0 :(得分:0)

您没有将正确的数字与误差范围进行比较,猜测的误差将是(guess * guess) - number(如果你的猜测是正确的,那么你的猜测误差与你得到的数字之间的差异)所以你需要一些东西沿着这条线:

public static double FindTheRoot(double previousG, int number)
{
    double errorMargin = 0.00001;
    double nextGuess = (previousG + number / previousG) / 2;
    double error = nextGuess * nextGuess - number;

    if (error < errorMargin)
        return nextGuess;
    else
        // ...