Java 递归将N项乘以2(二进制序列)
我的程序可以打印二进制序列;但这只是最后一个学期。 ex)N=12;2048Java 递归将N项乘以2(二进制序列),java,recursion,Java,Recursion,我的程序可以打印二进制序列;但这只是最后一个学期。 ex)N=12;2048 但我想让我的程序打印12 4 8 16 32 64 128 256 512 1024 2048。我丢失了在返回语句之前的count方法中包含print语句 大概是这样的: System.out.printf( "%5d", method( 12 ) ); System.out.println(); } public static int method( int 12 ){ if ( No == 1)
但我想让我的程序打印12 4 8 16 32 64 128 256 512 1024 2048。我丢失了在返回语句之前的count方法中包含print语句 大概是这样的:
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;
}
在您提到的例子中,递归方法不会将所有值返回给main方法,因此main不会打印序列。递归函数将其所有局部变量值存储在调用堆栈中(这是C、JAVA使用的数据结构)。因此,您要么将数据持久化到递归函数中,要么将其自身打印到递归函数中。有关递归中调用堆栈的一些知识将有助于理解。请参阅 如果您希望输入10的序列直到1024,请编辑main方法中的调用“count(N)to count(N+1)”,因为有11个数字,包括1024个 递归提醒了我一件奇妙的事情。尝试谷歌“递归”,你会得到你的意思是:递归点击会再次导致相同的搜索页面,从而导致递归的无限循环。:) 是的,我错过了“1”。
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;
}