几天前,我在这里问了一个关于Rabbits程序的问题,我设法ALMOST完成了它。问题是当我输入0时,它崩溃并且无法运行。有人可以帮帮我,这是我的任务:

将一对新生兔子(一只雄性,一只雌性)放在田里。兔子能够在一个月大的时候交配,因此在第二个月的月底,每对都会产生两对新的兔子,然后死亡。
注意:在第0个月中,有0对兔子。在第1个月,有1对兔子。

  • 使用while循环编写一个程序,该程序占用用户的月份数,并在该月末打印成对的兔子数。
  • 在同一cpp文件中,编写一个递归函数rabbits(),将月数作为输入,并在该月末返回对兔的对数。
  • 在主程序中,使用用户输入的编号调用函数rabbits()。输出两个计算(即您通过循环获得的计算和递归函数返回的计算),并查看它们是否相等。

  • #include <iostream>
    using namespace std;
    
    int rabbits (int);
    
    int main ()
    
    {
    int month_function, month_while, result_rec, result_while, counter = 0, rab_now, rab_lastmonth = 0, rab_twomonthsago = 1;
    
    cout << "Please enter the month. \n\n";
    cin >> month_function;
    month_while = month_function;
    cout << "\n";
    
    if (month_function % 2 == 0) // if month entered is even, the recursive function will use month - 1 because the total number of rabbits doubles every other month
    {
        month_function--;
    }
    
    result_rec = rabbits (month_function);
    
    while (counter < month_while)
    {
        if (counter % 2 == 0)
        {
        rab_now = rab_lastmonth + rab_twomonthsago;
        rab_lastmonth = rab_now;
        rab_twomonthsago = rab_now;
        }
        counter++;
        result_while = rab_lastmonth;
    }
    
    cout << "According to the recursive function, there are " << result_rec << " pairs of rabbits at the end of month " << month_while << "\n\n";
    
    cout << "According to the while loop, there are " << result_while << " pairs of rabbits at the end of month " << month_while << endl;
    
    if (result_rec = result_while)
    {
        cout << "\n";
        cout << "They are equal!" << endl;
    }
    else
    {
        cout << "They are not equal!" << endl;
    }
    
    return 0;
    }
    
    int rabbits (int month_function)
    
    {
        if (month_function == 0)
        {
            return 0;
        }
        else if (month_function == 1)
        {
            return 1;
        }
        else
        {
           return (rabbits (month_function - 2) + rabbits (month_function - 2));
        }
    }
    

    最佳答案

    您的问题在这里:

    if (month_function % 2 == 0) // if month entered is even, the recursive function will use   month - 1 because the total number of rabbits doubles every other month
    {
        month_function--;
    }
    

    如果输入0,则计算结果为true,因此month_function等于-1

    您(很可能)在逻辑上也有错误。如果为月份功能输入2,则将返回0,这是错误的。考虑一下输入2时应该得到什么答案,从那里确定应该很容易。

    07-25 20:30