'C++ program to find the closest number in the Fibonacci sequence

I need to write a program in C++ to find the closest Fibonacci number to the input number. I patched together a program that tells the Fibonacci number in the nth place, I've included it's code. Next is this task of finding the closest number to the input. What I've gathered is that I probably need to use a binary search/decision tree to rule out the bad numbers. I can generate the Fibonacci numbers so I'm that close. I need a point in the right direction to get me going. I'm pretty sure Binet's formula is involved as well as the golden ratio. Here's the code for my original program:

int fib(int n)

{
    if (n <= 1)
        return (n);
    return fib(n - 1) + fib(n - 2);
}

int main()
{
    cout << "Enter a number greater than -1 and see what the n'th place in the fibbonaci sequence equals.\n";
    cin >> n;
    fib(n);

    if (n >= 0)
        cout << "n'th Fibonacci number is " << fib(n) << "\n"; 
    else
        cout << "\nInvalid number.\n\n";
    return 0;
}


Solution 1:[1]

So I found some code that calculated the index for me. I made minor adjustments for input.

#include <iostream> 
using namespace std;

int findIndex(int n) 
{
    if (n <= 1) 
        return n; 

    int a = 0, b = 1, c = 1; 
    int res = 1; 
    while (c < n) 
    { 
        c = a + b; 
        res++; 
        a = b; 
        b = c; 
    } 
    return res; 
} 

int main() 
{ 
    int fib_number;
    cout << "Please enter a single integer number to see the closest index in the Fibonacci sequence.\n";
    cin >> fib_number;
    int result = findIndex(fib_number); 
    cout << "The Fibonacci index is " << result << "."; 
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan Dunnion