public class TestFib {
public static void main(String[] args) {
int n = f(5);
System.out.println(n);
}
public static int f(int x){
if(x==1 || x==2){
return 1;
}else{
return f(x-1)+f(x-2);
}
}
}
本文介绍了一个简单的Java程序,该程序使用递归方法来计算斐波那契数列的第5项。通过定义公共类TestFib并实现静态方法f,程序能够返回指定位置的斐波那契数值。
public class TestFib {
public static void main(String[] args) {
int n = f(5);
System.out.println(n);
}
public static int f(int x){
if(x==1 || x==2){
return 1;
}else{
return f(x-1)+f(x-2);
}
}
}
1238
508
2391

被折叠的 条评论
为什么被折叠?