C ++程序在斐波那契数列中找到最接近的数字

问题描述 投票:0回答:1

我有点困。我需要用C ++编写一个程序,以查找斐波那契数到输入数的闭合数。我拼凑了一个程序,该程序在第n位告诉斐波那契数,我已经包含了它的代码。接下来的任务是查找与输入最接近的数字。我迷上了数学。我一直在梳理互联网,寻找线索。我所收集的是,我可能需要使用二进制搜索/决策树来排除错误的数字。我可以生成斐波那契数,所以我就那么接近了。我需要朝着正确的方向迈出一步。我很确定Binet的公式以及黄金分割率都参与其中。这是我原始程序的代码:

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;
}
c++ fibonacci closest
1个回答
0
投票

因此,我找到了一些为我计算索引的代码。我对输入做了一些小的调整。

#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 << "."; 
} 
© www.soinside.com 2019 - 2024. All rights reserved.