黑马程序员技术交流社区

标题: 关于小兔子的古典问题 [打印本页]

作者: yanggangcl    时间: 2015-10-28 19:51
标题: 关于小兔子的古典问题

题目:古典问题:有一对兔子,从出生后第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个月前的总数)
作者: knight_zfh1288    时间: 2015-10-28 21:35
代码加点注释就更好了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2