1 /************************************************************************* 2 > File Name: 46_Accumulate.c 3 > Author: Juntaran 4 > Mail: JuntaranMail@gmail.com 5 > Created Time: 2016年09月04日 星期日 21时18分28秒 6 ************************************************************************/ 7 8 #include <stdio.h> 9 10 // 函数指针法求1+2+...+n 11 typedef unsigned int (*fun)(unsigned int); 12 13 unsigned int sum_T(int n) 14 { 15 return 0; 16 } 17 18 int Sum1(int n) 19 { 20 static fun f[2] = {sum_T, Sum1}; 21 return n + f[!!n](n-1); 22 } 23 24 // 递归 25 int Sum2(int n) 26 { 27 int sum = n; 28 int ans = (n>0) && (sum+=Sum2(n-1)); 29 return sum; 30 } 31 32 int main() 33 { 34 int n = 7; 35 int ret1 = Sum1(n); 36 int ret2 = Sum2(n); 37 printf("ret1 is %d ", ret1); 38 printf("ret2 is %d ", ret2); 39 40 return 0; 41 }