简体   繁体   English

为什么递归调用打印“ 123456”而不是“ 1”?

[英]Why does the recursive call print '123456' instead of '1'?

I'm having trouble understanding how the code is able to recover the remaining integers after they are taken off the original value via x/10. 我在理解代码如何通过x / 10去除原始值后如何恢复剩余整数时遇到麻烦。 Is there something going on behind the scenes? 幕后有什么事吗?

// precondition: x >= 0
// Question: What is printed from method call mystery(123456)?

public void mystery(int x) {
    if ((x/10) != 0) {
        mystery(x/10);
    }
    System.out.print(x % 10);
}

Each recursive call to mystery() happens before the final print statement that prints the digit. 每个对mystery()的递归调用都在最终打印该数字的打印语句之前进行。 The current state of the program is saved to the stack before the function begins to execute again, so on the last execution of the function, when x/10 = 0, the 1 is printed. 在函数再次开始执行之前,程序的当前状态已保存到堆栈中,因此在函数的最后一次执行时,当x / 10 = 0时,将打印1。 Then the program returns to the previous execution of the function, where x = 12, and continues to that print statement to print 12 % 10 = 2. This continues the same way until the program reaches the top level execution of the function. 然后,程序返回到该函数的先前执行,其中x = 12,并继续执行该打印语句以打印12%10 =2。这将以相同的方式继续进行,直到程序到达该函数的顶级执行为止。

This page explains recursion and has a useful diagram for the factorial example that shows how functions are called and returned. 该页面说明了递归,并提供了一个阶乘示例的有用图表,该示例显示了如何调用和返回函数。

Each invocation of mystery creates a new stack frame in the JVM. 每次神秘的调用都会在JVM中创建一个新的堆栈框架。 These frames are used to store parameters, local variables, and other data which I'll omit for brevity. 这些框架用于存储参数,局部变量和为简洁起见而省略的其他数据。 In your recursive step (mystery(x / 10)), each newly created stack frame will be holding a successively smaller copy of the result of x / 10. Once the base case is reached, each stack frame will then print the value of its copy of x % 10. 在递归步骤(mystery(x / 10))中,每个新创建的堆栈帧将保存x / 10结果的一个连续较小的副本 。一旦达到基本情况,每个堆栈帧将随后打印其值。 x%10的副本

So, for example, mystery(123456): 例如,mystery(123456):

  • Frame 1: 123456 框架1:123456
  • Frame 2: 12345 框架2:12345
  • Frame 3: 1234 相框3:1234
  • Frame 4: 123 镜框4:123
  • Frame 5: 12 框架5:12
  • Frame 6: 1 (Base case is reached! Each frame will now print and return) 框架6:1(已达到基本情况!现在将打印并返回每个框架)

Modulo 10 will always print the rightmost digit. Modulo 10将始终打印最右边的数字。 So that means after all the frames are finished, you will be left with 123456. If you are expecting 1, then how might you go about modifying your solution? 因此,这意味着在所有框架完成之后,您将剩下123456。如果期望值为1,那么您将如何修改您的解决方案? (Hint: think about base cases!) (提示:考虑基本情况!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM