遞迴(Recursion),是指在函式中使用函式自身的方法。
遞迴函式必須有終止條件,才能被計算。


#include<iostream>
using namespace std;
int f(int n)
{
if( n == 0 )
return 1;
if( n >= 1 )
return n*f(n-1);
}
int main()
{
int n;
while( cin >> n )
{
cout << f(n) << endl;
}
return 0;
}
1
3
5
1
6
120


#include<iostream>
using namespace std;
int f(int a, int b)
{
if( b == 0 )
return 1;
if( b >= 1 )
return a * f(a,b-1);
}
int main()
{
int a, b;
while( cin >> a >> b )
{
cout << f(a,b) << endl;
}
return 0;
}
2 4
3 3
5 2
16
27
25