C language brush questions - Crazy Rabbit

insert image description here

Article directory

topic

Classical problem : There is a pair of rabbits. From the third month after birth, a pair of rabbits is born every month. After the baby rabbit grows to the third month, another pair of rabbits is born every month. If the rabbits are not dead, ask each one. What is the total number of rabbits in a month?

insert image description here

ideas

The law of the rabbit is the sequence 1, 1, 2, 3, 5, 8, 13, 21... It conforms to the changing rules of the Fibonacci sequence. You can use loops or recursion to solve this problem.

answer

① Cycle

#include <stdio.h>

int main()
{
    
    
    long f1,f2;
    int i;
    
    f1=f2=1;
    
    for(i=1;i<=20;i++)
    {
    
    
        printf("%12ld %12ld",f1,f2);
        
        if(i%2==0)
        {
    
    
            printf("\n");    //控制输出,每行四个
        }

        f1=f1+f2;   //前两个月加起来赋值给第三个月
        f2=f1+f2;   //前两个月加起来赋值给第三个月
    }
}


② recursion

#include <stdio.h>


long countRabbit(long f)
{
    
    

    if(f==1 || f==2)
    {
    
    
        return 1;
    }
    else
    {
    
    
        return countRabbit(f-1) + countRabbit(f-2);
    }
}

int main()
{
    
    

   int month ;
   int i;

   printf("请输入月份:");
   scanf("%d",&month);

   for(i=1;i<=month;i++)
   {
    
    
       long f = countRabbit(i);

       printf("%12ld",f);

       if(i%4==0)
       {
    
    
           printf("\n");
       }

   }
   return 0;

}

Sample output

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/124001268
Recommended