基本介紹
一個函數在函數體內又調用了本身,稱爲遞歸調用
快速入門
當test(4)時,下面代碼輸出什麼,分析原因
int test( int n) { if(n>2) { test(n-1); } printf("n=%d\n",n); }
思路分析
當test=4時,test 4 >2 然後接着執行 test (4-1) 注意,此時的test(4)還未結束,printf還爲打印
當test(4-1)==>test(3)時,依舊>2 ,接着執行 test (3-1),此時test(3)還未結束,printf還爲打印
當test(3-1)此時==>test(2)不滿足條件>2, 即在test(2)中的返回值是 n=2,結束(test2);
然後到test(3)時,輸出打印結果 n=3,結束test(3);
然後到test(4),輸出打印結果 n=4,結束test(4);
完整代碼
#include<stdio.h>
int test( int n)
{
if(n>2)
{
test(n-1);
}
printf("n=%d\n",n);
}
int main()
{
test (4);
return 0;
}