費氏數列(fib)
程式碼:
/*費氏數列*/
import java.util.Scanner;
public class CH4_9{
static int fib(int n){
if (n <= 2) //前兩項唯1
return 1; //回傳1
return fib(n-1) + fib(n-2); //第n項 = (n-1)項 + (n-2)項
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in); //使用者輸入
System.out.print("fib:");
String s = sc.nextLine();
int n = Integer.parseInt(s); //字串轉整數
if(n < 0) { //n < 0並不存在
System.out.println("Cannot use negative numbers");
return;
}
for(int i = 1; i <= n; i++) //列前n項
System.out.print(fib(i) + ", ");
}
}
/* Output:
1, 1, 2, 3, 5,
*///:~

留言
張貼留言