[英]writing a method for fibonacci sequence
我正在尝试编写一个for循环,该循环调用方法fibonacci并打印fibonacci序列中的前25个数字。 问题是我对如何正确执行此操作有些困惑。
我对在run方法中的for循环何时调用fibonacci方法感到困惑不解,在到达for循环通过后,fibonacci方法内的值是否会重置? 因此,例如在for循环的第一遍过程中,i = 0,并且in a和int b的值在fibonacci方法内部发生了变化。 fibonacci方法内的值是否在for循环的下一遍重置?
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);
}
您正在两个不同的地方循环run()
和fibonacci()
。 这些位置中只有一个应关注循环,而另一个则应关注计算Fibonacci(n)。
我们可以做的是从fibonacci
删除循环,而仅依靠外部的循环。 另外,我们将删除该语句int n = 0
,因为它掩盖了您要传入的参数。
最后,我们将创建两个新的静态变量a
和b
,以便在此实例中保留这些变量的值。 如果您不这样做,则必须依靠递归或其他方法来提供a
和b
的适当值。
我不完全确定为什么需要扩展ConsoleProgram
,但是我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;
}
}
变量将为循环的每次迭代重置。 变量a
, b
和c
是仅在方法内“存在”的局部变量。 每次调用fibonacci(n)
方法都应从fibonacci序列的开头开始,并打印出直到第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++;
}
}
您没有存储fibonacci()的返回int值;
int currentSum=0;
for(int i = 0; i <= 25; i++){
currentSum+=fibonacci(i);
println(currentSum);
}
为什么在fibonacci(int n)中还有另一个变量n? 请首先确保您的斐波那契方法有效。 (无限的while循环等)
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.