Fibonacci使用数组

时间:2015-03-19 16:24:49

标签: java arrays for-loop

我尝试制作一个更简单的Fibonacci系列版本,结果证明它不起作用,没有时间去思考和压力,我可以从互联网的人那里得到一些帮助吗?谢谢!

import java.util.Scanner;

public class sq {


public static void main(String args[]){
int array[] = new int [100];

for(int i = 0; i <= 99; i++){
    array[i] = i;
}
int x  = 0;
for(int i = 0; i <= 98; x = array[i] + array[i+1] ){
    i++;
    System.out.print(x + " ");

 }

}
 }

2 个答案:

答案 0 :(得分:1)

测试此代码:

public class Fibonacci {



public static void main(String[] args) {
 int element = 0;
 String result;

 do {
 result = JOptionPane.showInputDialog("Insert a number.\n "
 + "Exit = -1");
 element = Integer.parseInt(result);

 } while ( element < -1 && element != -1);

 int before = 0;
 int now = 1;
 int next = 1;

 System.out.print("0, ");
 for (int i = 0; i < element - 1; i++) {
 System.out.print(next + ", ");

 next = now + before;
 before = now;
 now = next;
 }
 System.out.println();
 }
}

我希望这可以帮到你。

答案 1 :(得分:0)

public class sq {


    public static void main(String args[]){
        long array[] = new long [100];

        array[0] = 0;
        array[1] = 1;

        for(int i = 2; i < 100; i++){
            array[i] = array[i-1] + array[i-2];
        }

        for(int i = 0; i < 100; ++i ){
            System.out.print(array[i] + " ");
        }
    }
}

HTH