我试图用此程序打印斐波那契数列。我用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