【发布时间】:2021-07-10 03:10:48
【问题描述】:
谁能告诉我这行代码是如何工作的?
在这个给定的代码中,函数是如何被执行的? 即 tower(n-1, sourcePole, assistantPole,destinationPole);在这部分中,值是如何排列从而产生上述输出的。
https://www.geeksforgeeks.org/recursive-functions/
#include<stdio.h>
// Assuming n-th disk is bottom disk (count down)
void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole)
{
// Base case (termination condition)
if(0 == n)
return;
// Move first n-1 disks from source pole
// to auxiliary pole using destination as
// temporary pole
tower(n-1, sourcePole, auxiliaryPole,
destinationPole);
// Move the remaining disk from source
// pole to destination pole
printf("Move the disk %d from %c to %c\n",
n,sourcePole, destinationPole);
// Move the n-1 disks from auxiliary (now source)
// pole to destination pole using source pole as
// temporary (auxiliary) pole
tower(n-1, auxiliaryPole, destinationPole,
sourcePole);
}
int main()
{
tower(3, 'S', 'D', 'A');
return 0;
}
输出是
Move the disk 1 from S to D
Move the disk 2 from S to A
Move the disk 1 from D to A
Move the disk 3 from S to D
Move the disk 1 from A to S
Move the disk 2 from A to D
Move the disk 1 from S to D
【问题讨论】:
-
当函数调用自身时会发生递归。因此,当
tower()再次调用tower()时,递归发生在给定代码中的两个位置。这就是递归的工作原理。该算法非常透明。如果您无法在脑海中看到它,请拿起铅笔并手动执行说明。 -
好的,那么在调用过程之后 printf() 函数是如何产生这个输出的呢?
-
因为函数返回,然后 printf 被发出。诀窍是顶部的守卫
if( n==0)防止它永远递归。 -
好的,理解这段代码需要哪些先决条件?
-
逻辑和对 C 语法的基本了解。第一次调用时的参数是什么?
n是什么?接下来发生什么? cmets 实际上准确地解释了正在发生的事情。
标签: c function recursion data-structures