Java程序使用迭代和递归可以正确运行。但是出于某种奇怪的原因,我不明白的是,当我输入的数字大于9200时,我会得到一个StackOverFlow。我尝试将其更改为很长的时间,但这就是我能想到的。关于如何发生,为什么发生以及如何解决的任何想法是,它可以计算任何数字?

import java.util.Scanner;

public class Multiplication {

    public static long multiIterative(long a, long b) {
        long result = 0;
        while (b > 0) {
            result += a;
            b--;
        }
        return result;
    }

    public static long multiRecursive(long a, long b) {
        if (a == 0 || b == 0) {
            return 0;
        }
        return a + multiRecursive(a, b - 1);
    }

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        System.out.print("Please enter first Integer: ");
        long a = userInput.nextInt();
        System.out.print("Please enter second Integer: ");
        long b = userInput.nextInt();
        System.out.println("The Multiplication Iteration would be: " + multiIterative(a, b));
        System.out.println("The Multiplication Recursion would be: " + multiRecursive(a, b));
    }

}

最佳答案

在Java中,每个方法调用都会将激活记录放在堆栈上,直到完成为止。递归会产生与方法调用一样多的激活记录。因此,与在幕后实质上使用goto语句的迭代设计相比,递归算法不能无限深地运行。因此,这是递归算法设计的局限性之一。

考虑以下两个文件:IterationTest.java将永远快乐地运行(如果在Bash终端(例如Linux)中运行,请使用ctrl + c终止文件的执行),而RecursionTest.java将几乎立即失败。

/*
 * Runs perfectly fine forever
 * (use ctrl + c to escape execution in terminal, if on Linux)
 */
public class IterationTest
{
    public static void printMe()
    {
        while(true)
        {
            System.out.println("iteration");
        }
    }
    public static void main(String[] args)
    {
        printMe();
    }
}

/*
 * Guaranteed StackOverflow error using infinite recursion
 */
 public class RecursionTest
{
    public static void printMe()
    {
        System.out.println("iteration");
        printMe();
    }

    public static void main(String[] args)
    {
        printMe();
    }
}

关于java - 使用StackOverFlow进行奇怪的Java乘法递归,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28620176/

10-11 22:44
查看更多