递归 基线
factorial
#include<stdio.h> /* function prototype */ long factorial(long number); /* function main begins program execution */ int main(void) { int i; for(i=0; i<=10; i++) { printf("%2d!=%ld ",i,factorial(i)); } return 0; } /* recursivr definition of function factorial */ long factorial(long number) { /* base case */ if(number<=1) { return 1; } else { return number*factorial(number-1); } }
0!=1
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
10!=3628800
请按任意键继续. . .
#include <stdio.h> long fibonacci(long n); int main(void) { long result,number; printf("Enter an integer:"); scanf("%ld",&number); result=fibonacci(number); printf("Fibonacci(%ld)=%ld ",number,result); return 0; } long fibonacci(long n) { /* base case */ if(n==0 || n==1) { return n; } else { return fibonacci(n-1)+fibonacci(n-2); } }
#include <stdio.h> long fibonacci(long n); int main(void) { long result,start,end,number; int i; printf("Enter an integer-SATRT:"); scanf("%ld",&start); printf("Enter an integer-END:"); scanf("%ld",&end); for (i=start; i<=end; i++) { number = i; result=fibonacci(number); printf("Fibonacci(%ld)=%ld ",number,result); } return 0; } long fibonacci(long n) { /* base case */ if(n==0 || n==1) { return n; } else { return fibonacci(n-1)+fibonacci(n-2); } }
Enter an integer-SATRT:0
Enter an integer-END:11
Fibonacci(0)=0
Fibonacci(1)=1
Fibonacci(2)=1
Fibonacci(3)=2
Fibonacci(4)=3
Fibonacci(5)=5
Fibonacci(6)=8
Fibonacci(7)=13
Fibonacci(8)=21
Fibonacci(9)=34
Fibonacci(10)=55
Fibonacci(11)=89
请按任意键继续. . .