dimanche 27 mai 2018

Why my simple C++ fibonacci for negative numbers doesn't work?

I am learning C++ and I am trying to implement fibonacci generator for negative numbers. I totally don't understand what is wrong in my code. When I add condition for negative number, program each time ends with exit value (-1).

According to wiki: F(-n) = (-1)^(n+1) * F(+n)

http://cpp.sh/74fl2

#include <iostream>
#include <cmath>

int fibonacci_r(int num);

int main(){
    int n;
    std::cout << "Please provide number: ";
    std::cin >> n;

    std::cout << fibonacci_r(n);
    //std::cout << "F(" << n << ") = " << fibonacci_r(n);

    return 0;
}


int fibonacci_r(int n){
    if(n < 1){
        return std::pow(-1, n+1) * fibonacci_r(std::abs(n));
    }
    if(n == 1 || n == 0){
        return n;
    }
    else
        return (fibonacci_r(n-1) + fibonacci_r(n-2));
}

Aucun commentaire:

Enregistrer un commentaire