public class Test { public static void main(String[] args) { int month = new Scanner(System.in).nextInt(); System.out.println(getCount(month)); // 返回第month个月共有多少对兔子 }
public static int getCount(int i) { return i == 1 || i == 2 ? 1 : getCount(i - 1) + getCount(i - 2); } } 这其实是输出一个斐波那契数列 兔子的规律为数列1,1,2,3,5,8,13,21....
public class Test { public static void main(String[] args) { for(int i=1;i<=10;i++) System.out.println("第 "+i+" 个月兔子的总对数为:"+getTotalCount(i)); }
//返回第month个月刚刚出生的兔子对数 public static int getCount(int month) { return month == 1 || month == 2 ? 1 : month-1; }
//返回第month个月兔子的总对数 public static int getTotalCount(int month) { int sum =1; //第一对兔子
for(int i=1;i<=month;i++) sum += getCount(i);
return sum; } }
package javaapplication1;import javax.swing.*;public class Main { public static void main(String[] args) throws Exception { Main main=new Main(); int sum=0;
int year=Integer.parseInt(JOptionPane.showInputDialog("请输入年数"));
public class Test {
public static void main(String[] args) {
int month = new Scanner(System.in).nextInt();
System.out.println(getCount(month));
// 返回第month个月共有多少对兔子
}
public static int getCount(int i) {
return i == 1 || i == 2 ? 1 : getCount(i - 1) + getCount(i - 2);
}
}
这其实是输出一个斐波那契数列
兔子的规律为数列1,1,2,3,5,8,13,21....
public class Test {
public static void main(String[] args) {
for(int i=1;i<=10;i++)
System.out.println("第 "+i+" 个月兔子的总对数为:"+getTotalCount(i));
}
//返回第month个月刚刚出生的兔子对数
public static int getCount(int month) {
return month == 1 || month == 2 ? 1 : month-1;
}
//返回第month个月兔子的总对数
public static int getTotalCount(int month) {
int sum =1; //第一对兔子
for(int i=1;i<=month;i++)
sum += getCount(i);
return sum;
}
}
public static void main(String[] args) throws Exception {
Main main=new Main();
int sum=0;
int year=Integer.parseInt(JOptionPane.showInputDialog("请输入年数"));
int[] res=new int[3];
for(int i=1;i<=year;i++){
res=main.calculation(i);
for(int d=0;d<res.length;d++){
sum+=res[d];
}
System.out.println(sum);
sum=0;
}
}
int[] calculation(int yearA){
int[] n=new int[3];
int[] m=new int[3];
if(yearA==1)
{
n[2]=1;
}
if(yearA==2)
{
n[1]=1;
}
if(yearA>2)
{
m=this.calculation(yearA-1);
n[1]=m[2];
n[0]=m[1]+m[0];
n[2]=n[0];
}
return n;
}
}
public class Test1 { /**
* @param args
*/
public static int robbitNum(int month){
if(month>=3){
return robbitNum(month-1)+(month+1)/3 *2;
}
else{
return 2;
}
}
public static void main(String[] args) {
for(int i=1;i<20;i++){
System.out.println(robbitNum(i));
}
}
}
兔子的规律为数列1,1,2,3,5,8,13,21....楼上,这个题目等价于:1,1,2,3,5,8,13,21....
用递归算法,采用Java语言实现,如何实现?
5楼,顶