題目:撰寫程式讓使用者輸入想計算的費式數列個數,並由程式全部顯示出來
思考進程:
- 找出費式數列公式
- fn = fn-1 +fn-2 if n>1
- fn = n if n=0,1
- 抓入使用者輸入並轉成int
- 寫出費式數列迴圈並列印出數列,最後一位不印逗點
import java.util.Scanner;
public class Fibonacci{
public static void main (String args[]) {
System.out.printf("輸入你想要的個數");
Scanner sc = new Scanner(System.in);
int input = Integer.parseInt(sc.nextLine());
System.out.println(input);
if(input==0){
System.out.println("0");
}
else if(input==1){
System.out.println("0,1");
}
else{
int formerItem1=1;
int formerItem2=0;
int item=0;
System.out.print("0,1,");
for(int i=2;i<input;i++){
item = formerItem1 + formerItem2;
formerItem2=formerItem1;
formerItem1=item;
if(i!=input-1){
System.out.print(item+",");
}
if(i==input-1){
System.out.print(item);
}
}
}
}
}