首页 > 解决方案 > 斐波那契测试 (C++) 的错误结果

问题描述

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

我还尝试在 isFibonacci 函数中使用 do/while 循环而不是 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,这些数字都不是斐波那契数字。

标签: c++

解决方案


基本上你的方法是个好主意。但是您在检查功能中犯了一些实现错误。比如没有初始化变量和错误的计算。看看你的循环。

此外。大数字会有问题。

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

或者看看那本书:

Alfred Posamentierand Ingmar Lehmann 的(神话般的)斐波那契数

或者也在这里stackoverflow

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

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

推荐阅读