递归将N项乘以2(二进制序列)

时间:2014-10-29 03:11:00

标签: java recursion

   System.out.printf( "%5d", method( 12 ) );
   System.out.println();
}

public static int method( int 12 ){
   if ( No == 1){
      return 1;
   }

   int bob = 2 * method ( 12 - 1 );

   return bob;
}

我的程序可以打印二进制序列;但只是最后一个学期。 例)N = 12; 2048 但我希望我的程序打印1 2 4 8 16 32 64 128 256 512 1024 2048.我迷失了

2 个答案:

答案 0 :(得分:1)

在return语句之前的count方法中包含print语句

类似的东西:

   public static int count( int n ){
   if ( n == 1)
   {
      System.out.printf( "%15d", 1);
      return 1;
   }

   int nTerms = 2 * count ( n - 1 );
   System.out.printf( "%15d", nTerms );

   return nTerms;
}

答案 1 :(得分:0)

在你提到的情况下,递归方法不会将所有值都返回给main方法,因此main不会打印序列。递归函数将其所有局部变量值存储在callstack中(它是C,JAVA使用的数据结构) )。因此,您可以将数据保存在递归函数中,也可以将其打印在自身中。关于递归中的调用堆栈的一些知识将有助于理解。参考this link

如果您希望输入为10的序列直到1024,请在main方法中编辑调用“count(N)to count(N + 1)”,因为有11个数字包括1024.

递归让我想起了一个奇特的东西。尝试谷歌'递归',你会得到你的意思是:递归点击哪一个导致同一个搜索页面再次导致无限循环的递归。 :)