【问题标题】:How do you find fibonacci numbers in a range between two integers?如何在两个整数之间找到斐波那契数?
【发布时间】:2021-05-12 11:20:06
【问题描述】:

我正在创建一个 c++ 代码来输出两个数字之间的斐波那契数列。如果两个整数之间没有斐波那契数,我的部分代码将输出。例如,如果用户输入 9 和 12,代码将输出“无”。但是如果整数是 0 到 10,它会输出 0,1,1,2,3,5,8。以下是我目前的代码。

如果给定范围内没有任何斐波那契数,我将如何修复此代码以输出?现在,这段代码将读取(范围为 9 到 12),

NoneNoneNoneNoneNoneNone

#include <iostream>
#include <iomanip>
using namespace std;


int main(){
int high, low;

cout<< "Enter two integers: ";
cin>>low>>high;

int i=0;
int f1=0, f2 = 1,f3 = 1;
while (f1 <= high)

{

   
        f1 = f2;

        f2 = f3;

        f3 = f1 + f2;
    
    i++;
    
     if (f1>=low && f1<=high){
        
        cout<<setw(10)<<f1;
    }
    else{
        cout<<"None";
    }

    if (i != 0 && ((i % 6) == 0)){
        cout<<endl;
    }
    
    
}

return 0;
}

【问题讨论】:

  • 这个if (f1 &gt;= low){(第一个)说只有在f1大于下限时才计算斐波那契数。这真的是你想要的吗?当然,您要做的是计算斐波那契数,但如果它们大于下限,则仅打印它们。第二个if (f1&gt;=low)的作用,第一个可以去掉。

标签: c++ fibonacci


【解决方案1】:

所以,你计算的斐波那契数是正确的。

但你需要解耦。

  1. 斐波那契数的计算
  2. 范围检查,然后打印,如果在范围内
  3. 检查是否打印了某些内容。如果没有,则显示消息

您还应该使用正确的数据类型。斐波那契数快速增长。因此,强烈建议使用像 unsigned long long 这样的 64 位数据类型。

即便如此,对于 64 位值,也仅存在 93 个可能的 Fibancci 数。 (比内公式)。

一个可能的灵魂可能是这样的:

#include <iostream>

using ull = unsigned long long;

int main() {

    std::cout << "Inclusive range scan in Fibanocci series\n\nEnter the lower boundary and then the upper boundary:\n";
    
    // Get input values and check, if they are valid
    if (ull low{}, high{}; (std::cin >> low >> high) && (low < high)) {

        // Remeber, if some Fibonacci number could be found
        bool somethingWasFound{false};

        // Initial values of Fibonacci series
        ull f1{ 0 }, f2{ 1 }, f3{ 1 };

        // Search all Fibonacci numbers
        while (f1 <= high) {

            // If Fibonacci number is in range, the print it
            // No need to compare with high. This will be done in while statement
            if (f1 >= low) {
                std::cout << f1 << ' ';
                somethingWasFound = true;
            }
            // Calculate next Fibonacci number
            f1 = f2;
            f2 = f3;
            f3 = f1 + f2;
        }
        if (not somethingWasFound)
            std::cout << "\n\nNo Fibonacci number found in range: " << low << ',' << high << '\n';

    }
    else std::cerr << "\n\n*** Error: invalid input\n\n";

    return 0;
}

在启用 C++17 的情况下进行编译。分别设置你的编译器标志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多