我正在尝试使用此程序打印斐波那契数列。我使用了n=10
(要打印的斐波那契数字的数量),我得到了10个以上的数字。请您指出我错了吗?
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 ...
您的解决方案已经是迭代的了,包括while
循环。但是,您拨打的电话fib
数量减少了,大大增加了打印号码的数量。
删除递归调用,它将正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句