数兔子问题

编程实现:有一对兔子,从出生后第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. }





转载于:https://www.cnblogs.com/cfzhang/p/45dfa56ef97df91852e2c6a51b80a7e4.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值