递归函数练习——输出角谷猜想各个步骤

/*=====================================
角谷定理。输入一个自然数,若为偶数,则把它除以2,若为奇数,则把它乘以3加1。经过如此有限次运算后,总可以得到自然数值1。求经过多少次可得到自然数1。
如:输入22,
输出 22  11  34  17  52  26  13  40  20  10  5  16  8  4  2  1
     STEP=16

======================================*/
 1 #include<stdio.h>
 2 int step = 1;
 3 
 4 void fc(int n)//输出n这个数并按角谷猜想对n做处理以便进入下一步。返回值是总步数。 
 5 {
 6     if(n == 1)
 7     {
 8         printf("%d",n);
 9         return; 
10     }
11     else if(n%2 == 0)
12     {
13         printf("%d\t",n);
14         fc(n/2);
15         step++;
16     }
17     else
18     {
19         printf("%d\t",n);
20         fc(n*3+1);
21         step++;
22     }
23 }
24 
25 int main(int argc, char* argv[])
26 {
27     int n;
28     printf("Please input the num:");
29     scanf("%d",&n);
30     fc(n);
31     printf("\nStep = %d\n",step);
32     return 0;
33 }
View Code

 

posted on 2014-03-02 15:53  华山青竹  阅读(2042)  评论(0)    收藏  举报

导航