#include<stdio.h>int main() { int n; int sum1, sum2; printf("请输入要计算阶乘的数"); scanf("%d", &n); sum1 = factorial_1(n); sum2 = factorial_2(n); printf("sum1==%d,sum2==%d", sum1, sum2); return 0;}int factorial_1(int n) {//循环的方法 int i; int sum = 1; for (i = 1; i <= n; i++) { sum = sum * i; } return sum;}int factorial_2(int n) {//递归的方法 if (n == 1) return 1; else if (n > 1) { return n * factorial_2(n - 1); }}
可以看出 循环 和 递归 其实是可以互相表示的
练习4:
计算斐波那契数列(不算栈溢出)
#include<stdio.h>int Fibo1(int n);int Fibo2(int n);int main() { int n; int sum1, sum2; printf("请输入要计算Fibo的数"); scanf("%d", &n); sum1 = Fibo1(n); sum2 = Fibo2(n); printf("sum1== %d,sum2== %d", sum1, sum2); return 0;}//普通的递归方法int Fibo1(int n) { if (n == 1) return 1; else if (n == 2) return 1; else return Fibo1(n - 1) + Fibo2(n - 2);}int Fibo2(int n) { int a = 1; int b = 1; int c = 0; if (n == 1) { return a; } if (n == 2) { return b; } while (n > 2) { c = a + b; a = b; b = c; n--; } return c; //1 1 2 3 5 8 13 21 34 //a b c // a b c}
经典递归问题:
汉诺塔
#include<stdio.h>void Hanoi(int n, char A, char B, char C);int main() { int n =0; char A = 'A'; char B = 'B'; char C = 'C'; printf("请输入汉诺塔的层数(目标是将A柱移动到C柱)\n"); scanf("%d", &n); Hanoi(n,A,B,C); return 0;}void Hanoi(int n,char A, char B ,char C ) { if (n == 1) { printf("将%c-->%c\n",A,C); } else { Hanoi(n - 1, A, C, B);//将前n-1个 从 A 通过C 全部移到B printf("%c-->%c\n",A,C);//然后A最后一个大的到C Hanoi(n - 1, B, A, C);//最后B通过A到C }}