C language solves the problem of rabbit birth (small difficulty)!

Question: There is a pair of rabbits, and a pair of rabbits will be born every month from the third month after birth.
            After the little rabbit grows to the third month, another pair of rabbits will be born every month. Assuming that all the
            rabbits are not dead, what is the total number of rabbits in each month for 30 months?

Problem solving process:

The first is to draw a picture:

 Write the code according to the solution idea in the above figure:

#include"stdio.h"
#define row 31
#define col 5


// 初始化数组
void Init(long long arr[row][col], int R, int C)
{
    //  把第一个月的小兔,中兔,老兔初始化为1,0,0
    long long a = 1;
    arr[1][1] = a;
    arr[1][2] = 0;
    arr[1][3] = 0;

    // 第一列初始化为月份
    long long i = 0;
    for (i = 1; i < R; i++)
    {
        arr[i][0] = i;
    }
}




// 打印数组
void Dayin(long long arr[row][col], int R, int C)
{
    int i = 0, j = 0;
    for (i = 1; i < R; i++)
    {
        printf("第%3ld个月: 小兔:%7ld只   中兔:%7ld只   老兔:%7ld只    总数:一共%7ld只\n\n\n", (long long)arr[i][0], (long long)arr[i][1], (long long)arr[i][2], (long long)arr[i][3], (long long)arr[i][4]);
    }
}



//计算数组的每一个值
void JiSuan(long long arr[row][col], int R, int C)
{
    int i = 2;
    for (i = 2; i < R; i++)
    {
        long long XT = arr[i - 1][3];  // 小兔=上一行的老兔的只数
        long long ZT = arr[i - 1][1];  // 中兔=上一行的小兔的只数
        long long LT = arr[i - 1][2] + arr[i - 1][3];  // 老兔=上一行的中兔+上一行的老兔
        long long ZS = XT + ZT + LT;   //  总数= 小兔+中兔+老兔

        // 把这一行的小兔,中兔,老兔,总数的值填上
        arr[i][1] = XT;
        arr[i][2] = ZT;
        arr[i][3] = LT;
        arr[i][4] = ZS;

    }

}

int main()
{
    long long arr[row][col] = { 0 };
    //初始化数组
    Init(arr, row, col);

    

    //计算数组的每一个值
    JiSuan(arr, row, col);


    // 打印数组
    Dayin(arr, row, col);



    return 0;
}

Final result:

 

Now I feel that all the problems need to be drawn. By drawing, I will clear up my thoughts first, and the rest of writing code is a very easy thing. Well, today's study is over! In fact, this question was considered yesterday, and I didn’t draw the picture. After thinking about it at night, I finally finished it today! I am still a little excited, because the problems to be solved are getting more and more complicated!

Guess you like

Origin blog.csdn.net/xingyuncao520025/article/details/131339556