黑马程序员技术交流社区
标题:
提问,大家帮我解答一下,怎么写?给个思路也行
[打印本页]
作者:
mysouffle
时间:
2014-8-22 22:23
标题:
提问,大家帮我解答一下,怎么写?给个思路也行
有一对兔子,从出生后第3个月起每个月都生一对兔子,
小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,
问第20个月的兔子对数为多少?
作者:
┣┫流枫
时间:
2014-8-22 22:30
和裴波那契数列一样 当前项是前两项的和 第一二项为1
作者:
hejinzhong
时间:
2014-8-22 22:30
这个是循环打印每个月的,如果要20,就不要循环,直接传个20过去
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
public class exp2{
public static void main(String args[]){
int i=0;
for(i=1;i<=20;i++)
System.out.println(f(i));
}
public static int f(int x)
{
if(x==1 || x==2)
return 1;
else
return f(x-1)+f(x-2);
}
}
或
public class exp2{
public static void main(String args[]){
int i=0;
math mymath = new math();
for(i=1;i<=20;i++)
System.out.println(mymath.f(i));
}
}
class math
{
public int f(int x)
{
if(x==1 || x==2)
return 1;
else
return f(x-1)+f(x-2);
}
}
复制代码
作者:
TheBest__^
时间:
2014-8-23 20:47
楼上正解
作者:
lhtwm1
时间:
2014-8-23 21:27
这是 哪段视频阶段的题哦
作者:
mysouffle
时间:
2014-8-23 21:57
lhtwm1 发表于 2014-8-23 21:27
这是 哪段视频阶段的题哦
没看视频,不知道视频上有木有
作者:
mysouffle
时间:
2014-8-23 22:00
谢谢大家解答,感激不尽啊
作者:
小黑子
时间:
2014-8-23 22:12
月份 兔子对数
1 1
2 1
3 2
4 3
5 5
6 8
7 13
/*
思想:
从第2个月开始,上一个月是可产仔数量,本月是已有数量。
下月 = 本月 + 上月
*/
class Fibonacci
{
public int getFibonacci(int month)
{
int f1,f2;
f1=0;
f2=1;
if(month <= 0)
{
System.out.println("input error");
return -1;
}
//因为已经设置第1个月,f2=1,故month=1无需运行for
for(int x=1;x<month;x++)
{
f1 = f1 + f2;
//交换结束后,始终保持f1为上月,f2为本月
f1^=f2;
f2^=f1;
f1^=f2;
}
return f2;
}
}
class FibonacciDemo
{
public static void main(String[] args)
{
int num;
num = new Fibonacci().getFibonacci(7);
System.out.println("num = "+num);
}
}
复制代码
其实很简单,LZ只要记住这个公式就OK了:
下月 = 本月 + 上月
作者:
sunny~
时间:
2014-8-23 23:04
斐波拉契序列 一模一样的
作者:
MeryStyle
时间:
2014-8-23 23:15
前两个月都是一对兔子,从第三个月开始,每个月兔子的对数都是之前相近两个月兔子对数的和。变样的斐波拉契数列,思路就是这样!
作者:
mysouffle
时间:
2014-8-26 22:05
感受到了大家的热情
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2