Recursive Function to generate / print a Fibonacci series

前端 未结 4 535
情书的邮戳
情书的邮戳 2020-12-21 18:55

I am trying to create a recursive function call method that would print the Fibonacci until a specific location:

1 function f = fibonacci(n)
2 fprintf(\'The          


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 19:40

    Try this:

     function f = fibonacci(n)
     if (n==1)
         f= 1;
     elseif (n == 2)
         f = 2;
     else
         f = fibonacci(n-1) + fibonacci(n-2);   
     end
    

    Note that this is also a recursion (that only evaluates each n once):

    function f=fibonacci(n)
      f=additive(n,1,2);
    
    function a=additive(n,x0,x1)
      if(n==1)
        a=x0;
      else 
        if(n==2)
          a=x1;
        else 
          a=additive(n-1,x1,x0+x1);
        end
      end
    

提交回复
热议问题