從前有一對長壽兎子,它們每一個月生一對兎子,新生的小兎子兩個月就長大了,在第二個月的月底開始生它們的下一代小兎子,這樣一代一代生下去,求解兎子增長數量的.數列。以下是小編為大家搜尋整理的C語言兎子產子程式碼,歡迎閱讀!更多精彩內容請及時關注我們應屆畢業生考試網!
*問題分析與演算法設計
問題可以抽象成下列數學公式:
Un=Un-1+Un-2
其中:
n是項數(n>=3)。它就是著名的斐波那契數列,該數列的前幾為:1,1,2,3,5,8,13,21...
斐波那契數列在程式中可以用多種方法進行處理。按照其通項遞推公式利用最基本的迴圈控制就可以實現題目的要求。
*程式說明與註釋
#include
int main()
{
int n,i,un1,un2,un;
for(n=2;n<3;)
{
printf("Please enter required number of generation:");
scanf("%d",&n);
if(n<3) printf("n Enter error!n"); /*控制輸入正確的N值*/
}
un=un2=1;
printf("The repid increase of rabbits in first %d generation is as felow:n",n);
printf("ltlt");
for(i=3;i<=n;i++)
{
un1=un2;
un2=un;
un=un1+un2; /*利用通項公式求解N項的值*/
printf(i%10?"%dt":"%dn",un);
}
printf("n");
}
*執行結果
Please enter required number of generation: 20
The repid increase of rabbits in first 20 generation is as felow:
1 1 2 3 5 8 13 21 34 55
89 144 233 377 610 987 1597 2584 4181 6765