代码略显粗糙
有可优化的地方可以留言指教,不胜感激
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
System.out.println("Enter the number of Fibonacci you want to find");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
//调用方法
method1 a = new method1();
int res = a.array(num);
System.out.println("res= " + res);
}
}
//定义斐波那契方法
class method1{
public int array(int n){
//n>2时,返回前两个斐波那契数的相加
if( n > 2){
return array(n-1) + array(n-2);
}else{//0和1 的情况下,返回值1
return 1;
}
}
}