小牛問題

描述:農場有一頭牛,每年生一頭小牛。小牛四歲後會每年生一頭小小牛。求20年後農場有多少頭牛。

             題目很短,但很有意思的題目,作爲水平不是很高的我來說,我覺得起到了充分的鍛鍊。

思路:  第一年:0  1;第二年:1  +  1  = 2 ;第三年:1  +  2  = 3;   .......  ; 第九年:5  +  14=19  ....

實現:#include <iostream>
              using namespace std;
              int main()
            {
              int newborn=0,a0=0,a1=0,a2=0,a3=0,total=1,willbe=1;
              cout<<0<<": "<<total<<endl;
              for(int i=1;i<=20;i++)
            {
                willbe=a3+willbe;
                newborn=willbe;
                 a3=a2;
                 a2=a1;
                 a1=a0;
                 a0=newborn;
                 total=newborn+total;
                 cout<<i<<": "<<total<<endl;
               }
               system("pause");
                return 0;
           }

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章