A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yanggangcl 中级黑马   /  2015-10-28 19:51  /  734 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月
   后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
  1. #include <stdio.h>

  2. int main(int argc, const char * argv[]) {
  3.    
  4.     long n, n_1, n_2, months;
  5.     n = 1;
  6.     n_1 = 1;
  7.     n_2 = 1;
  8.     months = 50;
  9.     for (int i = 1; i < months; i++) {
  10.         if (i == 1||i == 2) {
  11.             printf("this month, the total number is:%ld\n", n);
  12.         }else {
  13.             n = n_1 + n_2;
  14.             printf("this month, the total number is:%ld\n", n);
  15.             n_2 = n_1;
  16.             n_1 = n;
  17.         }
  18.     }
  19.     return 0;
  20. }
复制代码

关键是找到规律:
规律第N个月的数量,是由第N-1个月的数量 + 新生的数量(新生的数量等于N-2个月前的总数)

1 个回复

倒序浏览
代码加点注释就更好了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马