我試圖用此程序打印斐波那契數列。我用n=10
(斐波那契數字打印),我得到了超過10個數字。請你能指出我哪裏錯了嗎?java斐波那契數列錯誤:沒有得到正確的輸出
import java.util.*;
class myprogram{
static int f=0,s=1,sum=0;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.printf("Enter the number of numbers you want to print");
int n=sc.nextInt();
System.out.print(f+" "+s);
fib((n-2));
}
static void fib(int count){
while(count!=0)
{
sum=f+s;
System.out.print(" "+sum);
f=s;
s=sum;
count-=1;
fib(count);
}
}
}
輸入:
n=10
預期輸出:
0 1 1 2 3 5 8 13 21 34
我的輸出:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 ...
remove fib(count);從你的fib(int count)方法結束。 –
這是一個巨大的錯誤。感謝您指出。 – sakyan
我用'if(count> 0)'替換'while(count!= 0)',因爲我使用的是遞歸。 – sakyan