編寫Java程式,接受使用者輸入一個數據為上限,然後10個一行輸出不超過上限的所有Fibonacci數

  • 作者:由 匿名使用者 發表于 遊戲
  • 2021-08-13

編寫Java程式,接受使用者輸入一個數據為上限,然後10個一行輸出不超過上限的所有Fibonacci數張滌萍891020 2013-06-24

public static void main(String[] args) {

Scanner input = new Scanner(System。in);

System。out。println(“請輸入上限數”);

int max = input。nextInt();

for (int j = 0; j < getNum(max)。length; j++) {

if(j%10==0){

System。out。println();

}

System。out。print(getNum(max)[j] + “ ”);

}

}

public static int[] getNum(int n) {

int[] nums = new int[n];

for (int i = 0; i < n; i++) {

if (i < 2) {

nums[i] = 1;

} else {

nums[i] = nums[i - 1] + nums[i - 2];

}

}

return nums;

}

編寫Java程式,接受使用者輸入一個數據為上限,然後10個一行輸出不超過上限的所有Fibonacci數hardneedl 2013-06-24

/**

* 把序列抽象出來

* @author Hardneedl

* @param  序列中的資料型別

*/

interface Sequence {

/**

* 獲取序列中位置n上的物件

*

* @param n 位置

* @return 位置n上的物件

*/

T get(int n);

}

/**

* 斐波那契數列

* @author Hardneedl

*/

class Fibonacci implements Sequence {

public Integer get(int n) {

if (n < 0) throw new RuntimeException(“n must >= 0”);

if (n == 0 || n == 1) return n;

return get(n - 1) + get(n - 2);

}

}

/**

* @author Hardneedl

*/

public class FibonacciDemo {

public static void main(String。。。 args) {

final int LIMIT_UP = Integer。parseInt(args[0]);

Sequence sequence = new Fibonacci();

for(int i = 1,j=0; i <= LIMIT_UP; j++,i++){

if (j>9){

j = 0;

System。out。println();

}

System。out。print( sequence。get(i) + “\t”);

}

}

}

Top