[英]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.