斐波那契痕迹

时间:2013-10-02 23:06:27

标签: java recursion fibonacci

我只想提前做好这是一项家庭作业。我已经用很多不同的方式尝试过这个问题,而我只是出于想法而没有获得所需的输出。

问题

编写一个程序,跟踪Fibonacci数字是如何递归生成的(对于任何N)并以下列方式显示跟踪:

示例(N = 4):

Entering level 0
Entering level 2
Entering level 4
Exiting level 4
Entering level 3
Exiting level 3
Exiting level 2
Entering level 1
Entering level 3
Exiting level 3
Entering level 2
Entering level 4
Exiting level 4
Entering level 3
Exiting level 3
Exiting level 2
Exiting level 1
Exiting level 0

我的主要:

public class A5main {

public static void main(String[] args) {
    //n holds user input
    //level is the current level of the tree
    //fibonacci is a5class object
    int n;
    int level=0;
    a5class fibonacci= new a5class();
    Scanner keyboard = new Scanner(System.in);

    //Ask user for input

   System.out.println("Enter a number up to which Fibonacci series to print: ");
   n = keyboard.nextInt();
   System.out.println("Fibonacci trace of: " + n);

    //Pass input to fibonacci.trace method with arguments n, level.
   fibonacci.trace(n,level);

}
}

我的课程:

 package a5main;
 public class a5class {
    int fibWork;
   public a5class()     
{ 
}
public int trace(int t, int level)
{
    //Accepts t and level as an argument.
    //Lets uer know what level they are entering 
    System.out.println("Now entering level " + level);
    //If t<=1 just return the value
        if (t<=1)
        {
            System.out.println ("\tNow exiting level " + level);
            return t;

        }
        //Else use recurssion to figure out the fibonacci sequence
        //and determine what level you are on.
        else
        {
            fibWork = trace(t-1, level+1) + trace(t-2, level+1);
            System.out.println ("\tNow exiting level " + level);
            return t; 
        }
}
}

(我把它放在那里,所以我现在可以看到它在哪里更容易退出)

我的输出:

Enter a number up to which Fibonacci series to print: 
4
Fibonacci trace of: 4
Now entering level 0
Now entering level 1
Now entering level 2
Now entering level 3
     Now exiting level 3
Now entering level 3
     Now exiting level 3
     Now exiting level 2
Now entering level 2
     Now exiting level 2
     Now exiting level 1
Now entering level 1
Now entering level 2
     Now exiting level 2
Now entering level 2
     Now exiting level 2
     Now exiting level 1
     Now exiting level 0

我还尝试不将'level传递给方法,并且在创建对象时在我的公共a5class中将其等于0但到目前为止还没有运气。

虽然我的距离可能不太远,但我注意到它退出了3级,然后在下一个序列中重新进入它,这似乎也不合逻辑。

我感谢任何帮助或指导。即使只是一个正确方向的指针也很受欢迎。我认真对待我的编程,并希望真正理解它。我不想“假装”我的方式,并且有一个毫无价值的程度。

谢谢!

1 个答案:

答案 0 :(得分:2)

从预期的输出中你会看到程序希望直接从级别0进入级别2,级别4从级别2进入。这只有在第一次递归调用中向级别添加2时才会发生:

fibWork = trace(t-2, level+2) + trace(t-1, level+1);