Print a string of fibonacci recursively in C#

前端 未结 11 686
你的背包
你的背包 2020-12-29 16:05

Can that be done with no while loops?

static void Main(string[] args)
{
    Console.WriteLine(\"Please enter a number\");
    int number = Convert.ToInt32(C         


        
11条回答
  •  自闭症患者
    2020-12-29 16:37

    That's a way to do it by returning a value into the main.

    public static void Main() {

        Console.WriteLine("Introduce the number");
        int num = Convert.ToInt32(Console.ReadLine());
    
        int num1 = 1, num2 = 1, counter = num-2; 
    

    //Take 2 out to match the list as first 2 numbers doesn't count in the function.

        Console.WriteLine(Fibo(num1, num2, counter));
    }
    
    public static int Fibo(int num1, int num2, int counter)    {
    
        int temp = num1;
    
        if (counter <= 0)
            return num2;
        else
            return Fibo(num1 = num2, num2 += temp, counter-1);
    }
    

提交回复
热议问题