C+±026-递归调用-2020-3-9
阶乘
//n的阶乘
#include<iostream>
using namespace std;
int factorial(int n)
{
int f;
if(n<0)
cout<<"错误的输入";
else if(n==0||n==1)
f=1;
else
f=factorial(n-1)*n;
return(f);
}
int main ()
{
int n;
cin>>n;
cout<<n<<"!="<<factorial(n);
return 0;
}
9
9!=362880
--------------------------------
Process exited with return value 0
Press any key to continue . . .
汉诺塔1
//汉诺塔1
#include<iostream>
using namespace std;
/*将n个金片从one座到two座,移到three座*/
void hanoi(int n,char one,char two,char three)
{
if(n==1)//当金片只剩下一个小时
cout<<one<<"->"<<three;//移动金片从one到three
else
{
hanoi(n-1,one,three,two);//递归调用,金片数-1,三个针换位置
cout<<one<<"- "<<three;//移动金片从one到three
hanoi(n-1,two,one,three);//递归调用,金片数-1,三个针换位置
}
}
int main()
{
int m;//金片数
cout<<"请输入金片数";
cin>>m;
hanoi(m,'A','B','C');
return 0;
}
汉诺塔-2-最少需要移动的次数
/*
汉诺塔2 fun(x)=(((1*2+1)*2+1)*2+1)...=2^n-1
*/
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n;
cin>>n;
cout<<pow(2,n)-1<<endl;
return 0;
}