Results 1 to 6 of 6

Thread: Fibonacci in C++

  1. #1
    Join Date
    Oct 2008
    Posts
    20

    Fibonacci in C++

    Im actually kinda embarassed to ask this question.

    Code:
    #include <iostream>
    int main() {
    unsigned long long a = 1;
    unsigned long long b = 1;
    for (int i = 0; i < 45; i++) {
    a += b;
    std::cout << a/b << std::endl;
    b += a;
    std::cout << b/a << std::endl;
    }
    std::cin.get();
    }
    Why cant i get it to work?

  2. #2
    Join Date
    Jul 2008
    Posts
    92

    Re: Fibonacci in C++

    What do you expect from your program? What seems to be the problem?

  3. #3
    Join Date
    Oct 2008
    Posts
    20

    Re: Fibonacci in C++

    I want to end up with the number 1.618, or something like it, but i have trued everything it seems, it will only print integers, i should
    know why, but either i've forgotten how this work (a int working a lotwith float/double) or i am just stupid.

    If you remove the /a and /b from the code u'll see that it does indeed work, but those are not the numbers i want.

  4. #4
    Join Date
    Aug 2008
    Posts
    46

    Re: Fibonacci in C++

    Here is a recursive algorithm:

    Code:
    int fibonacci( int i ) {
    if ( i == 0 ) return 0;
    if ( i == 1 ) return 1;
    else return fibonacci( i - 1 ) + fibonacci( i - 2 );
    }
    
    And non-recursive:
    
    int fibonacci( int i ) {
    int result[] = { 0, 1 };
    while ( i > 1 ) {
    int t = result[0];
    result[0] = result[1];
    result[1] = result[0] + t;
    --i;
    }
    return result[i];
    }
    
    int main() {
    for ( int i = 0; i < 45; ++i )
    cout << i << ": " << fibonacci( i ) << '\n';
    }

  5. #5
    Join Date
    Jul 2008
    Posts
    92

    Re: Fibonacci in C++

    When you divide a integer by an integer, you get an integer. What you want is to convert one of them to double before dividing, like double(a)/b

  6. #6
    Join Date
    Mar 2008
    Posts
    101

    Re: Fibonacci in C++

    It seems he wants a series converging (slowly) to the golden ratio, or something like that.

    The problem is that he performs an integer division instead of a floating point division.

    Here are some ways of forcing a floating point division in C++:

    double(a)/b instead of a/b
    1.0*a/b instead of a/b
    (a+0.0)/b instead of a/b

    double a instead of unsigned long long a;

    We should note, however, that the above is not a standard C++ program since there is no "long long" type in C++.

    C++ does have a "long double" type.

Similar Threads

  1. java coding for fibonacci series
    By Jagadamba in forum Software Development
    Replies: 3
    Last Post: 17-11-2009, 10:44 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,266,696.66685 seconds with 17 queries