我正在尝试编写一个调用方法fibonacci的for循环,并在fibonacci序列中打印前25个数字。问题是我对如何正确地做到这一点感到困惑。
我有点困惑的是,当run方法中的for循环调用fibonacci方法时,fibonacci方法中的值是否在到达for循环后重置?因此,例如在for循环的第一次传递期间i = 0并且int a和int b的值在fibonacci方法内部发生变化。在for循环的下一次传递中,fibonacci方法中的值是否重置?
import acm.program.*;
public class Fibonacci extends ConsoleProgram{
private void run(){
for(int i = 0; i <= 25; i++){
fibonacci(i);
println(fibonacci(i));
}
}
private int fibonacci(int n){
int n = 0;
int a = 0;
int b = 1;
while (n < 25);
int c = a + b;
a = b;
b = c;
}
return(a);
}
答案 0 :(得分:1)
您正在两个不同的地方循环 - run()
和fibonacci()
。这些地方中只有一个应该关心循环,而另一个应该关心计算Fibonacci(n)。
我们可以做什么从fibonacci
中删除循环,并且只依赖于外部的循环。此外,我们将删除该语句int n = 0
,因为这会影响您传入的参数。
最后,我们将创建两个新的静态变量a
和b
,以便使用此实例保留这些变量的值。如果您不这样做,那么您必须依靠递归或其他方法来提供a
和b
的适当值。
我不完全确定你为什么需要延长ConsoleProgram
,但我现在就把它留下来。
所以,这就是它的样子。
public class Fibonacci extends ConsoleProgram {
static int a = 0;
static int b = 1;
public void run() {
for(int i = 0; i <= 25; i++) {
// Print the call to fibonacci(i) with every iteration.
}
}
private int fibonacci(int n) {
int c = a + b;
a = b;
b = c;
return c;
}
}
答案 1 :(得分:1)
Fibonacci这是一个典型的算法示例,可以通过递归轻松接近,这是因为:
因此,如果您应用与之前相同的步骤,则只需取消所有内容,这意味着当您的计数器为0时,您必须执行与先前步骤不同的操作,并且它是:
答案 2 :(得分:0)
为循环的每次迭代重置变量。变量a
,b
和c
是仅在方法中“生效”的局部变量。对fibonacci(n)
方法的每次调用都应从斐波纳契序列的开头开始,并打印出直到第n个项的条件。因此,while (n < 25);
不应该是方法的一部分。此外,int n = 0
将n重置为零,这很糟糕,因为我们需要知道n是什么来获得第n个项。
执行此循环的理想方法是:
private void fibonacci(int n) {
int i = 1; // a new variable i to count from the 1st term
int a = 0; // the first term
int b = 1; // the second term
while (i <= n) {
int c = a + b; // the new value for b
a = b; // switch the old a for the new a
b = c; // get the (i + 1)th term for the next iteration
System.out.println(a); // print out the ith term
i++;
}
}
答案 3 :(得分:-1)
您没有存储fibonacci();
的返回int值int currentSum=0;
for(int i = 0; i <= 25; i++){
currentSum+=fibonacci(i);
println(currentSum);
}
为什么你的斐波纳契(int n)中有另一个变量n? 请确保首先使用斐波那契方法。 (无限循环等)。
public static void main (String args[]){
for(int i = 0; i<25; i++) {
System.out.println(fibonacci(i));
}
}
static int fibonacci(int n){
if(n==0) {
return 0;
}
int a = 0;
int b = 1;
for(int i = 0; i < n; i++){
int temp = b;
b += a;
a = temp;
}
return(b);
}