某公司的算法题,借此在网上搜了答案,贴出来勉励。

    技术2022-05-19  25

    有一对兔子,从出生后第三个月起每个月都生一对小兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数是多少?

     

    using System ; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rabbit { class Program { static void Main(string[] args) { int x; Console.Write("请输入月份数"); x = Convert.ToInt32(Console.ReadLine()); int i = test(x)/2; Console.WriteLine(x + "个月后的兔子有" + i + "对"); Console.ReadLine(); } public static int test(int n) { if (n < 1) { return 1; } else if (n == 2) { return 2; } else { return test(n - 1) + test(n - 2); } } } }  

     

    实际上是斐波那契数。


    最新回复(0)