Java中递归函数的返回。

huangapple go评论58阅读模式
英文:

Java return with recursion function

问题

我开始学习Java我有一个任务要创建一个递归函数我在查找关于Java中递归的信息时找到了一些有趣的代码我无法理解当n等于10时为什么在return后面的n变成了9然后当k等于9时return后面k = 10

public class lvl22666 {

    public static void main(String[] args) {
        recTest(0,10);
    }

    static void recTest(int n, int k) {
        if (n == k) {
            return;
        } else {
            if (n < k) {
                n++;
                System.out.println(n + " " + k);
                recTest (n,k);
            }
            if (k > n) {
                k--;
                System.out.println(n + " " + k);
                recTest (n,k);
            }
        }
    }
}
英文:

I'm starting learning Java. I have a task to make a recursion function. I was looking for information about recursion in Java and found some interesting code. I can't understand, when n equals 10, why n after "return" n equals 9. And then, when k equals 9, after "return" k = 10.

 public class lvl22666 {

	public static void main(String[] args) {
		recTest(0,10);
	}

	static void recTest(int n, int k) {
		if (n == k) {
			return;
		} else {
			if (n &lt; k) {
				n++;
				System.out.println(n + &quot; &quot; + k);
				recTest (n,k);
			}
			if (k &gt; n) {
				k--;
				System.out.println(n + &quot; &quot; + k);
				recTest (n,k);
			}
		}
 	}
}

答案1

得分: 4

所有递归方法都有三个要素:

  1. 退出条件,以防止无限循环
  2. 工作项,
  3. 递归调用。

在你的递归函数中,退出条件是:

if (n == k)
   return;

工作项是:

n++;
System.out.println(n + " " + k);

除非k大于n,此时工作项是:

k--;
System.out.println(n + " " + k);

递归调用是:

recTest(n, k);

请注意,由于返回操作会提前退出方法,因此不需要else语句。

要理解递归方法的行为,首先必须理解什么是堆栈帧,堆栈的工作原理,以及它如何用于在方法调用之间保存状态。

当Java准备调用一个方法时,它将调用方法的局部变量,包括其参数(总称为方法的“状态”)和调用方法的返回地址,放入一个堆栈帧中,然后将该堆栈帧推入堆栈中。然后它调用新方法。

当Java从方法返回时,它弹出堆栈帧,恢复调用方法的原始状态。

堆栈就像你在50年代餐馆旋转木马上看到的盘子堆栈;堆栈中的第一个盘子是洗碗工放进去的最后一个盘子。我们将其称为后进先出(LIFO)队列。

稍加想象,你可以看到对递归方法的连续调用将保留在每次递归期间对状态所做更改的运行历史。由于在每次递归期间都保存了状态的副本,因此可以通过从方法调用返回来返回到状态的先前步骤。

英文:

All recursive methods have three things:

  1. An exit condition, to prevent an endless loop
  2. A work item, and
  3. A recursive call.

The exit condition in your recursive function is:

if (n == k)
   return;

The work item is:

n++;
System.out.println(n + &quot; &quot; + k);

Unless k is greater than n, in which case the work item is:

k--;
System.out.println(n + &quot; &quot; + k);

The recursive call is:

recTest (n,k);

Note that, since a return early-exits you out of the method, the else statement is not required.

To understand the behavior of a recursive method, you must first understand what a stack frame is, how the stack works, and how it serves to preserve state between method calls.

When Java prepares to call a method, it puts the calling methods' local variables including its parameters (collectively, the method's "state") and the return address of the calling method into a stack frame, and pushes that stack frame onto the stack. It then calls the new method.

When Java returns from a method, it pops the stack frame off the stack, restoring the calling method's original state.

A stack is like the stack of plates you see in the carousel at a 50's diner; the first plate off the stack is the last plate the dish washer put there. We call this a last-in, first-out (LIFO) queue.

With a little imagination, you can see how successive calls to a recursive method will keep a running history of any changes made to the state during each recursion. Since a copy of the state is saved during each recursion, you can walk back to a previous step in the state by returning from a method call.

答案2

得分: 0

这个函数的功能是循环遍历它,直到 n 等于 k。

if (n == k) {
    return;

这个部分检查 n 是否等于 k,如果是真的,则返回到主函数。如果不是,它会检查两个数字中哪个较小,并将其加一。然后,函数使用 n 和 k 的新值调用自身,整个函数重复执行。如前所述,这将一直进行,直到 n 等于 k,触发返回。这退出函数并跳转到下一行代码(在 recTest(0,10); 之后)。

如果你有任何进一步的问题,不要害怕问!

英文:

What this function does is iterate through it, until n equals k.

if (n == k) {
        return;

This checks if n equals k and returns to the main function, if this is true.
If not, it checks which of the two numbers is smaller and adds it by one.
After doing that, the function calls itself with the new values of n and k and the whole function repeats. As stated earlier, this is done until n is equal to k which triggers a return. This exits the function and jumps to the next line of code (after recTest(0,10);).

If you have any further questions don't be afraid to ask!

huangapple
  • 本文由 发表于 2020年10月11日 04:06:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64297761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定