主题:求助啊 递归
1065793881
[专家分:0] 发布于 2011-10-13 22:02:00
怎么去理解hanoi塔程序啊,虽然用递归实现代码不多,但是,跟着它一步一步走就晕了,我们应该怎样更好的使用和理解递归啊!!!求救啊!!!!!
回复列表 (共3个回复)
沙发
cgl_lgs [专家分:21040] 发布于 2011-10-14 10:29:00
以状态和功能为单位去理解,而不是以语句为单位。
板凳
laowang [专家分:90] 发布于 2011-10-16 21:54:00
所谓递归函数就是直接或者间接调用自己的函数。了解递归函数是如何工作的,知道函数中所声明的变量是如何存储的。当函数被调用时,它的变量的空间是创建于运行时椎再的,以前调用的函数的变量仍保留在堆再上。
例如有一个整数4267,我们要把它的每一个数字依次输出,也就是依次输出4 2 6 7
我们可以用递归来实现这个功能
void binary_to_ascii(unsigned int value)
{
unsigned int quotient;
quotient = value / 10;
if(quotient != 0)
binary_to_ascii(quotient);
putchar(value%10 + '0');
}
下面是变量的存储情况
value 4267 quotient 空
______________________________
value 4267 quotient 426
_________________________________
value 426 quotient 空
value 4267 quotient 426
_____________________________
value 426 quotient 42
value 4267 quotient 426
____________________
value 42 quotient 4
value 426 quotient 42
value 4267 quotient426
______________________________
value 4 quotient 0
value 42 quotient 4
value 426 quotient 42
value 4267 quotient426
当quotient=0时,不再调用自己本身了。注意在递归函数中,总存在这样一个条件让函数终结,现在函数要销毁堆再上的变量了,椎再的特点是先进后出。所以上面的先出来。
先出来4 4+‘0’ 变成了字符4打印出来。
再出来42 42%10=2 所以2打印出来
再出来426 426%10=5 所以6打印出来
再出来4267 4267%10=4 所以打印出来7,顺序是对的吧?
3 楼
lijiaoyand [专家分:50] 发布于 2011-10-18 18:18:00
我也不懂啊
SIGNATURE:-----------------------------------
Imagination is more important than knowledge.
[url=http://www.vipfrees.com/nike-free-run-2-c-32.html]nike free run 2[/url] , [url=http://www.vipfrees.com/nike-lunarglide-3-c-31.html]nike lunarglide 3[/url] , [url=http://www.vipfrees.com/nike-free-30-c-37.html]nike free 3.0[/url]
我来回复