作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我只是想提前说明这是一项家庭作业。我已经尝试了很多不同的方法来解决这个问题,以至于我不知道为什么我没有得到想要的输出。
编写一个程序来跟踪斐波那契数是如何递归生成的(对于任何 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);
}
}
我的类(class):
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;
}
}
}
(我把\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 传递给方法,并在创建对象时在我的公共(public) a5class 中将其设置为 0,但到目前为止还没有成功。
虽然我的可能离得不远,但我注意到它退出了第 3 级,然后在下一个序列中重新进入,这在逻辑上似乎也不正确。
我感谢任何帮助或指导。即使只是指向正确方向的指针也会受到赞赏。我认真对待我的编程并想真正理解它。我不想“假装”通过它并获得一文不值的学位。
谢谢!
最佳答案
从预期的输出中,您会看到程序希望直接从 0 级进入 2 级,并从 2 级进入 4 级。只有在第一次递归调用中将 2 添加到该级别时才会发生这种情况:
fibWork = trace(t-2, level+2) + trace(t-1, level+1);
关于java - 斐波那契轨迹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148239/
我是一名优秀的程序员,十分优秀!