数兔子问题

编程实现:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第3个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?


C代码     
  1. long int get_rabbits_cnt(long int month)
  2. {
  3. long int cnt = 1;
  4. long int cnt_pre = 0;
  5. long int cnt_prepre = 0;
  6. long int i;
  7. for(i = 1; i < month; i++)
  8. {
  9. cnt_prepre = cnt_pre;
  10. cnt_pre = cnt;
  11. cnt = cnt_pre+cnt_prepre;
  12. }
  13. return cnt;
  14. }

java代码
  1. public class HelloWorld {
  2. private static Scanner scan;
  3. public static void main(String []args){
  4. scan = new Scanner(System.in);
  5. long rabbits = 0;
  6. long month = 0;
  7. while(true)
  8. {
  9. System.out.println("输入想查询的月数");
  10. // 判断是否还有输入
  11. if(scan.hasNextLine()){
  12. String str2 = scan.nextLine();
  13. System.out.println("输入的数据为:"+str2);
  14. month = Integer.parseInt(str2);
  15. rabbits = calculate_rabbit(month);
  16. }
  17. System.out.println("month: "+month+" rabbits pair: "+rabbits+" number: "+(rabbits<<1));
  18. }
  19. }
  20. private static long calculate_rabbit(long month) {
  21. // TODO Auto-generated method stub
  22. long cnt = 1;
  23. long cnt_pre = 0;
  24. long cnt_prepre = 0;
  25. long i;
  26. for(i = 1; i < month; i++)
  27. {
  28. cnt_prepre = cnt_pre;
  29. cnt_pre = cnt;
  30. cnt = cnt_pre+cnt_prepre;
  31. }
  32. return cnt;
  33. }
  34. }



来自为知笔记(Wiz)


posted on 2017-08-28 11:20  cfzhang  阅读(179)  评论(0编辑  收藏  举报

导航