2 回答
TA贡献1809条经验 获得超8个赞
你的斐波那契类看起来像这样吗?
class FibonacciExample1{
public static void main(String args[]){
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);
for(i=2;i<count;++i) {
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
TA贡献1794条经验 获得超8个赞
如果我必须这样做,我会选择不同的方法 - 但这是你的程序,所以我只修复了你的错误:
public class Fibonacci {
private int n;
private int fib1;
private int fib2;
private int fib3;
public Fibonacci(int ny){
n=ny;
fib1=1;
fib2=1;
fib3=0;
}
public int nextNumber() {
while(n-->2) {
fib3=fib1+fib2;
fib1=fib2;
fib2=fib3;
}
return fib3;
}
public int getFib1() {
return fib1;
}
public int getFib2() {
return fib2;
}
}
public class FibonacciGenerator{
public static void main(String[] args) {
Scanner sd = new Scanner(System.in);
System.out.println("Enter the amount of fibonaccis you want: ");
int ny = sd.nextInt();
Fibonacci num = new Fibonacci(ny);
System.out.println(num.getFib1());
System.out.println(num.getFib2());
for(int i = 3; i < ny; i++){
num = new Fibonacci(i);
System.out.println(num.nextNumber());
}
}
}
添加回答
举报