斐波那契数列

题目: 输入一个阶数,输出该阶数对应的斐波那契数列。

斐波那契数列:
斐波那契数列(Fibonacci sequence).
其值为f(n)=f(n-1)+f(n-2).
f(0)=0;
f(1)=1;

java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package fibonacci;
import java.util.Scanner;
public class fibonacci {
public static void main(String[] args) {
System.out.println("please input a number");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(n<0) {
System.out.println("it's error");
}else {
for(int i=0;i<=n;i++) {
int sum = fibonacci(i);
System.out.println("i="+i+" "+sum);
}
}
}
public static int fibonacci(int n) {
int sum=0;
if (n==0) {
sum = 0;
return sum;
}
else if(n==1) {
sum = 1;
return sum;
}
else {
sum=fibonacci(n-1)+fibonacci(n-2);
return sum;
}
}
}
  • 1、sum=fibonacci(n-1)+fibonacci(n-2);这条语句是核心。这会使这个方法不断的进行迭代处理,知道最后n=0.