繁体   English   中英

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

[英]C++ program to find the closest number in the Fibonacci sequence

我有点卡住了。 我需要用 C++ 编写一个程序来找到输入数字的收盘斐波那契数。 我拼凑了一个程序,它告诉第 n 位的斐波那契数,我已经包含了它的代码。 接下来是寻找与输入最接近的数字的任务。 我迷失了数学。 我一直在网上搜索线索。 我收集到的是,我可能需要使用二叉搜索/决策树来排除坏数字。 我可以生成斐波那契数列,所以我很接近。 我需要一个正确的方向来让我前进。 我很确定比奈的公式和黄金比例都有关。 这是我的原始程序的代码:

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;
}

所以我找到了一些为我计算指数的代码。 我对输入做了微小的调整。

#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 << "."; 
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM