1 , 1 , 2 , 3 , 5 , 8 , 13 ……
求此数列的第N个项
用一维数组来做:
import java.util.*;
public class shulie {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“输入数字:”);
int n = sc.nextInt();
int[] x= new int [n];
for(n=0;n<x.length;n++)
{
if(n==0||n==1)
{
x[n]=1;
}
else
{
x[n]=x[n-2]+x[n-1];
}
}
System.out.println(x[n-1]);
}
}
用递归来做:
import java.util.*;
public class shulie {
public static int shuzu(int n)
{
int shuzi;
if(n==1||n==2)
{
shuzi = 1;
}
else
{
shuzi = shuzu(n-2)+shuzu(n-1);
}
return shuzi;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“输入数字:”);
int a = sc.nextInt();
int x = shuzu(a);
System.out.println(x);
}
}