函数不能嵌套定义,但能嵌套调用(在调用一个函数的过程中再调用另一个函数)
函数间接或直接调用自己,称为递归调用
汉诺塔问题
思想:简化为较为简单的问题 n=2
较为复杂的问题,采用数学归纳方法分析
递归什么时候终止:只剩一个圆盘的情况 A--到--B
费波纳茨数列
根据最大公约数的如下3条性质,采用递归法编写计算最大公约数的函数Gcd(),在主函数中调用该函数计算并输出从键盘任意输入的两正整数的最大公约数。
性质1 如果a>b,则a和b与a-b和b的最大公约数相同,即Gcd(a, b) = Gcd(a-b, b)
性质2 如果b>a,则a和b与a和b-a的最大公约数相同,即Gcd(a, b) = Gcd(a, b-a)
性质3 如果a=b,则a和b的最大公约数与a值和b值相同,即Gcd(a, b) = a = b
#include <stdio.h> int Gcd(int a, int b); int main() { int a, b, c; printf("Input a,b:"); scanf("%d,%d", &a, &b); c = Gcd(a, b); if (c!=-1) printf("Greatest Common Divisor of %d and %d is %d ", a, b, c); else printf("Input number should be positive! "); getchar(); getchar(); return 0; } int Gcd(int a, int b) { if (a<=0||b<=0) return -1; if (a == b) return a; else if (a > b) return Gcd(a-b, b); else return Gcd(a, b-a); }