函数的嵌套使用
栈保存了当前现场和返回地址(第九章会讲)单步调试可以看
例3.7 求两个数的平方和
//求两个数的平方和
#include <iostream>
using namespace std;
int fun2(int m){
return m * m;
}
int fun1(int x, int y){
return fun2(x) + fun2(y);
}
int main() {
int a,b;
cout <<"Enter two integers: ";
cin >> a >> b;
cout << " The sum of square of a and b: " << fun1(a,b) << endl;
return 0;
}
函数的递归调用
定义:函数直接或间接的调用自身,成为递归调用
例3.8:计算n!
//计算n!
#include <iostream>
using namespace std;
unsigned fac(int n){
unsigned f;
if(n == 0)
f = 1;
else
f = fac(n-1) * n;
return f;
}
int main() {
int n;
cout <<"Enter a positive integer: ";
cin >> n;
cout << " The ans is : " << fac(n) << endl;
return 0;
}
例3.9 用递归法计算从n个人中选k个人组成一个委员会的不同组合数。
思路:比如三个人中选两个人,两个人中选两个人+两个人中选一个人
//用递归法计算从n个人中选k个人组成一个委员会的不同组合数。
#include <iostream>
using namespace std;
int comm(int n, int k){
if (k > n)
return 0;
else if(k == n || k == 0)
return 1;
else
return comm(n-1,k) + comm(n-1,k-1);
}
int main() {
int n, k;
cout <<"Enter two integers(n,k): ";
cin >> n >> k;
cout << " The ans is : " << comm(n,k) << endl;
return 0;
}
例3.10 汉诺塔问题
思路需要好好想一下,栈的概念还是不理解。
// 例3.10 汉诺塔问题
#include <iostream>
using namespace std;
//将src针的最上面的一个盘子移动到dest针上
void move(char src,char dest){
cout << src << "-->" << dest << endl;
}
void hanoi(int n, char src, char medium, char dest){
if(n == 1)
move(src, dest);
else{
hanoi(n-1, src, dest, medium);
move(src, dest);
hanoi(n-1,medium, src, dest);
}
}
int main() {
int m;
cout <<"Enter the number of diskes: ";
cin >> m;
cout << " The step to moving : " << m << "diskes:" << endl;
hanoi(m,'A','B','C');
return 0;
}
3个盘子 移动7次 公式讲解