黑马程序员技术交流社区
标题:
关于小兔子的古典问题
[打印本页]
作者:
yanggangcl
时间:
2015-10-28 19:51
标题:
关于小兔子的古典问题
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月
后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
#include <stdio.h>
int main(int argc, const char * argv[]) {
long n, n_1, n_2, months;
n = 1;
n_1 = 1;
n_2 = 1;
months = 50;
for (int i = 1; i < months; i++) {
if (i == 1||i == 2) {
printf("this month, the total number is:%ld\n", n);
}else {
n = n_1 + n_2;
printf("this month, the total number is:%ld\n", n);
n_2 = n_1;
n_1 = n;
}
}
return 0;
}
复制代码
关键是找到规律:
规律第N个月的数量,是由第N-1个月的数量 + 新生的数量(新生的数量等于N-2个月前的总数)
作者:
knight_zfh1288
时间:
2015-10-28 21:35
代码加点注释就更好了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2