斐波那契检验(C++)的结果错误

Wrong results for fibonacci-test (C++)

本文关键字:结果 错误 C++ 检验      更新时间:2023-10-16

我开始学习C++,我的功课是写一个代码,你可以输入5个数字,程序会告诉你每个数字是否是斐波那契数。

我还尝试在 isFibonacci 函数中使用 do/while-loop 而不是 for 循环,但这并没有解决问题。

#include <iostream>
#include <cstdio>
using namespace std;
//function to test whether a number is a Fibonacci number or not
bool isFibonacci (int i) 
{
    //special cases with 0 and 1:
    if ( i == 0 || i ==1) {
        return true;  
    } 
    //for all other numbers:
    int Fib1;
    int Fib2;
    int Fib3;
    for (Fib3=0; Fib3>=i; Fib3++) {
        Fib3 = Fib1 + Fib2;
        Fib1 = Fib2;
        Fib2 = Fib3;
        if (Fib3==i){
            return true;
        } 
        else {
            return false;
        } 
    }
} 
int main () 
{
    bool result;
    int numbers[5]; 
    int i;
    //asking for the 5 numbers
    cout << "Please enter 5 numbers;" << endl;
    cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
    // giving back the result
    for (i=0; i<5; i++) {
        result=isFibonacci (numbers[i]);
        if (result == true) {
            cout << "Your number " << numbers[i] << " is a Fibonacci  number!" << endl;
        } 
        else {
            cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << endl;
        } 
    } 
    return 0; 
}  

第一个斐波那契数是(0(,1,1,2,3,5,8,12。因此,当我输入 5 个数字时,例如 1,2,3,4,5,我应该得到 1、2、3 和 5 的"是",但 4 应该得到"否"。但是,我的程序声称除了 1 之外,这些数字都不是斐波那契数。

基本上你的方法是个好主意。但是您在检查函数中犯了一些实现错误。就像未初始化的变量和错误的计算一样。然后看着你循环。

此外。大数字会有问题。

许多非常聪明的人探索了斐波那契数。有整本书可用。也是维基百科文章。看这里。

或者看看那本书:

阿尔弗雷德·波萨门蒂埃和英格玛·莱曼的(神话般的(斐波那契数字

或者也在这里堆栈溢出

因此,我不会重新发明轮子。这是您修改后的软件:

#include <iostream>
#include <cmath>
#include <numeric>

// Positive integer ? is a Fibonacci number
// If and only if one of 5?2 + 4 and 5?2 - 4 is a perfect square
// from The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
// Function to test whether a number is a Fibonacci number or not
bool isFibonacci(int w)
{
    {
        double x1 = 5 * std::pow(w, 2) + 4;
        double x2 = 5 * std::pow(w, 2) - 4;
        long x1_sqrt = static_cast<long>(std::sqrt(x1));
        long x2_sqrt = static_cast<long>(std::sqrt(x2));
        return (x1_sqrt * x1_sqrt == x1) || (x2_sqrt * x2_sqrt == x2);
    }
}
int main()
{
    bool result;
    int numbers[5];
    int i;
    //asking for the 5 numbers
    std::cout << "Please enter 5 numbers;" << std::endl;
    std::cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
    // giving back the result
    for (i = 0; i < 5; i++) {
        result = isFibonacci(numbers[i]);
        if (result == true) {
            std::cout << "Your number " << numbers[i] << " is a Fibonacci  number!" << std::endl;
        }
        else {
            std::cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << std::endl;
        }
    }
    return 0;
}