TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
一个农夫养了一头牛,三年后,这头牛每一年会生出1头牛,生出来的牛三年后,又可以每年生出一头牛……问农夫10年后有多少头牛?n年呢?(不考虑其他因素,只考虑此数学问题) 这个题用java写有两种思路,一般人会想到的第一种方法是递归,但是有一种更经典的思路:面向对象 1.递归(结果为28,如果要算n年后的结果,只需将10改为n):
- public class Cow {
- static int count = 1;
- private static void feedCow(int year,int age){
- year++;
- age++;
- if(year<=30){
- if(age>=3){
- count++;
- feedCow(year,0);
- }
- feedCow(year,age);
- }
- }
-
- public static void main(String[] args) {
- new Cow().feedCow(0, 0);
- System.out.println(count);
- }
- }
复制代码
2.面向对象(很经典的思路,结果当然是28,要求n年后,只需将i<=10改为i<= n
- public class Cow {
- public static int count = 0;
- public Cow(int year){
- count++;
- for(int i=3+year;i<=10;i++){
- new Cow(i);
- }
- }
-
- public static void main(String[] args) {
- new Cow(0);
- System.out.println(count);
- }
- }
复制代码
- 30年后居然可以生出[b]58425[/b]头牛…
复制代码
源码下载:http://file.javaxxz.com/2014/11/10/000224093.zip |
|