2014-10-29 26 views
1
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; 
} 

我的程序可以打印二进制序列;但只有最后一届。 ex)N = 12; 2048 但我想我的程序打印1 2 4 8 16 32 64 128 256 512 1024 2048我迷路递归N乘以2(二进制序列)

回答

1

包括在计数方法print语句只是return语句

这样的事情之前, :

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; 
} 
+0

是的,我错过了“1”。 – JosEduSol 2014-10-29 03:32:32

0

在这种情况下,你已经提到的,递归方法亘古不变的所有值恢复为主要方法,因此主不会打印sequence.A递归函数存储在调用栈所有的局部变量值(它是数据结构由C,JAVA使用)。因此,您要么将数据保存在递归函数中,要么将其自身打印出来。有关递归调用堆栈的一些知识将有助于理解。请参阅this link

在你期望的序列,直到1024的10的输入的情况下,编辑呼叫“计数(N)进行计数(N + 1)”主的方法,因为有11个数字,包括1024

递归提醒我一个奇特的事情。尝试谷歌的递归',你会得到你的意思是:递归点击,导致同一个搜索页面再次导致无限循环的递归。 :)