1,1,2,3,5,8,13,21,33···
用递归算法写上面程序
1,1,2,3,5,8,13,21,33···
用递归算法写上面程序
package com.zhrea.test.test;
public class TestOne {
public static void main(String[] args) { int k = 0; int j = 0; for(int i =0; i< 30; i++){ if(i < 2){ k = 1; j=1; }else{ k = k+j; j=k-j; } System.out.print(k+","); }
}
}
import javax.swing.JOptionPane; public class Fibonacci { int F(int n) { if(n==0) return 1; else if(n==1) return 1; else if(n>1) return F(n-1)+F(n-2); else JOptionPane.showMessageDialog(null,"方程无解!"); return 0; } public static void main(String[] args) { int i,n,m; Fibonacci f=new Fibonacci(); String s=JOptionPane.showInputDialog(null,"please input n:\n"); n=Integer.parseInt(s); for(i=0;i<=n;i++) { m=f.F(i); System.out.print(m+" "); } } }
结果: