有一头母牛,当年年初生一头小母牛,每头小母牛出生第四年年初(算当年,即三年后)也生一头小母牛,问20年后共有多少头母牛?
#include <stdio.h>
int main() {int i, firstYear, secondYear, thirdYear, forthYear;firstYear = 2;secondYear = 3;thirdYear = 4;for (i = 4; i <= 20; i++) {forthYear = firstYear + thirdYear;firstYear = secondYear;secondYear = thirdYear;thirdYear = forthYear;}printf("%d", forthYear);return 0;
}
迭代的特点:当前计算变量x值是基于前一次x的结果,计入新一轮的迭代之前,新的值替换老的值.