Calculating Fibonacci Numbers Recursively in C

后端 未结 6 1210
名媛妹妹
名媛妹妹 2021-01-14 01:52

I\'m trying to learn C by writing a simple program to output Fibonacci numbers. It isn\'t working.

fibonacci.h

unsigned int fibonacc         


        
6条回答
  •  心在旅途
    2021-01-14 02:49

    Your approach seems strange, you should have:

    • a main file (example main.c) with the main method and that includes fibonacci.h
    • a fibonacci.h with the prototype unsigned int fibonacci_recursive(unsigned int n);
    • a fibonacci.c with the implementation of the method, and it should include fibonacci.h too

    Actually you define main function twice too..

    main.c

    #include 
    #include "fibonacci.h"
    
    main()
    {
        unsigned int i;
        for (i = 0; i < 10; i++)
        {
            printf("%d\t%n", fibonacci_recursive(i));
        }
        getchar();
    }
    

    fibonacci.h

    unsigned int fibonacci_recursive(unsigned int n);
    

    fibonacci.c

    #include "fibonacci.h"
    unsigned int fibonacci_recursive(unsigned int n)
    {
        if (n == 0) 
        {
            return 0;
         } 
         if (n == 1) {
               return 1;
         }
         return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
    }
    

提交回复
热议问题