函式递回
13 函式递回的理解:
13.1 (使用函式)数数字的练习
#include <stdio.h> void countTo1 (int); int main() { countTo1(1); return 0; } void countTo1(int i) { if (i <= 3) { countTo1(i+1); printf("%d\n", i); // 这里的另一种写法是 printf("%d\n", i); countTo1(i+1); } }
13.2 (使用函式)求连续整数和的练习(有递回)
#include <stdio.h> int sum(int N); int main() { int N; printf("N = "); scanf("%d", &N); printf("%d\n", sum(N)); return 0; } int sum (int N) { if (N == 1) { return 1; } return sum(N-1) + N; } N = 1000 500500 Process returned 0 (0x0) execution time : 20.777 s Press any key to continue.
13.3 求上楼梯的方法数的练习
#include <stdio.h>
int S(int);
int main() {
int N;
printf("N = ");
scanf("%d", &N);
printf("%d\n", S(N));
return 0;
}
int S(int N) {
if (N <= 2) {
return N;
}
return S(N-1) + S(N-2);
}
N = 10
89
Process returned 0 (0x0) execution time : 4.986 s
Press any key to continue.