Fibonacci数字不应该从它应该开始

时间:2014-10-29 15:00:06

标签: java fibonacci

我正在尝试使用for循环来制作斐波纳契序列,不幸的是,当我运行该方法(下面列出)时,它不会像它应该的那样从0开始。当它应该为0时,第一个数字总是2。如果任何人都可以向我解释如何使序列以0开头,那将是很好的。谢谢。

public static final void fibonacci(){
    int num = 1;
    int num2 = 1; 
    int tnum = 0; 
    int startnum = 1; 
    System.out.println("Please input a number:"); 
    Scanner input = new Scanner(System.in); 
    int x = input.nextInt(); 
    for(int i = 0; i < x; i++){ 
        System.out.print(num + num2 + " "); 
        tnum = num; 
        num = num2; 
        num2 = tnum + num2; 
    }
}

2 个答案:

答案 0 :(得分:0)

你应该从

开始
num = 0

然后打印num,并修改num(然后在你的第i个循环中,num是第i个斐波纳契数:

public static final void fibonacci() {
    int num = 0;
    int num2 = 1;
    int tnum = 0;
    int startnum = 1;
    System.out.println("Please input a number:"); 
    Scanner input = new Scanner(System.in); 
    int x = input.nextInt();
    for (int i = 0; i < x; i++) {
        System.out.print(num);
        tnum = num + num2;
        num = num2;
        num2 = tnum;
    }
}

答案 1 :(得分:0)

public static final void fibonacci(){
    int num = -1; //was "1"
    int num2 = 1; 
    int tnum = 0; 
    int startnum = 1; 
    System.out.println("Please input a number:"); 
    Scanner input = new Scanner(System.in); 
    int x = input.nextInt(); 
    for(int i = 0; i < x; i++){ 
        System.out.print(num + num2 + " "); 
        tnum = num; 
        num = num2; 
        num2 = tnum + num2; 
    }
}

这是我得到的输出:

*请输入一个数字:

9

0 1 1 2 3 5 8 13 21 *