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;
}我的程序可以打印二进制序列,但只能打印最后一个项。但我要我的程序打印1,2,4,8,16,32,64,128,256,512,2048。我迷路了
发布于 2014-10-29 03:22:00
在返回语句之前的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;
}发布于 2014-10-29 04:10:47
在前面提到的情况下,递归方法不会将所有值返回给main方法,因此main不会打印顺序,递归函数将其所有局部变量值存储在一个调用堆栈中(它是C,JAVA使用的数据结构)。因此,您可以将数据保存在递归函数中,也可以将其打印在那里。有关递归调用堆栈的一些知识将有助于understanding.Refer 此链接。
如果您期望输入为10的序列一直到1024,请在主方法中编辑调用"count(N) to count(N+1)“,因为其中有11个数字,包括1024。
递归让我想起了谷歌‘递归’的一个奇特的thing.Try,你会得到--您的意思是:递归单击,它再次导致相同的搜索页面,导致无限循环的递归。:)
https://stackoverflow.com/questions/26622162
复制相似问题