反斐波那契数列

时间:2018-10-23 22:56:35

标签: c++ visual-c++

我被分配了一个必须创建反向斐波那契数列的问题。当比率为-3.23607时,表示收敛。我不确定为什么它不会输出num,但我认为它与while循环有关。提前致谢。

#include <iostream>
using namespace std;

void reverseFibonacci(int*, int*);


// Driver function 
int main()
{
int a, b;
int *ptr_1 = &a;
int *ptr_2 = &b;
cout << "what are points 1 and 2?" << endl;
cin >> *ptr_1 >> *ptr_2;
reverseFibonacci(ptr_1, ptr_2);
return 0;
}

void reverseFibonacci(int *a, int *b)
{
int *ptr1 = a;
int *ptr2 = b;
int c = *ptr1 - *ptr2;
int *ptr3 = &c;


int num = 0;


do
{
    *ptr3 = *ptr1-*ptr2;
    *ptr2 = *ptr1;
    *ptr1 = *ptr3;
    num++;
} while (((*ptr1 / *ptr2) + (*ptr2 / *ptr3)) >= -3.23607);

cout << num << endl;

int *q = new int[num];

for (int f = 0; f < num; f++)
{
    q[f] = *ptr1;
    q[f + 1] = *ptr2;
    c = *a - *b;
    *b = *a;
    *a = c;
}


for (int j = num - 1; j >= 0; j--) 
{
    cout << q[j] << " ";
}

delete[] q;
}

1 个答案:

答案 0 :(得分:0)

您的代码中有几个问题。 例如,在计算(* ptr1 / / ptr2)+(* ptr2 / * ptr3))中,您将int除以得到int,而不是我想像的两倍。

在项计算中也存在一些错误(我假设“ a”是逆序列的第一项,如果我错了,请原谅我)。 对于q []表的计算,仅计算q [0]和q [1]。假设此q []直接对应于斐波那契数列,我对此进行了纠正。

我认为没有必要使用指向int的指针而不是int。我修改了它,但也许这不是您的选择。

我插入了一些中间值的书写:我使用它们来更正代码。我让他们向您展示调试程序的可能方法。 我还使用了向量而不是C数组。如果需要,您可以轻松返回阵列。除此之外,我尝试遵循您自己的代码,而不修改所有内容。

由于我可能已经修改了ptr1和ptr2的含义,请检查收敛性测试(“比率”)的计算是否正确。

这是代码,似乎可以工作:

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

void reverseFibonacci(int, int);
int main()
{
    int a, b;
    cout << "what are points 1 and 2?" << endl;
    cin >> a >> b;
    reverseFibonacci(a, b);
    return 0;
}

void reverseFibonacci(int a, int b)
{
    const int num_max = 100;
    int ptr1 = a;
    int ptr2 = b;
    int ptr3;

    cout << "a = " << a << "\tb = " << b << "\n";
    int num = 0;
    double ratio;
    do
    {
        ptr3 = ptr1-ptr2;
        ptr1 = ptr2;
        ptr2 = ptr3;
        if ((ptr2 != 0) && (ptr3 != 0))
            ratio = static_cast<double> (ptr1) / ptr2 + static_cast<double>(ptr2) / ptr3;
        else
            ratio = -100.0; 
        cout << "num = " << num << "\t\tptr2 = " << ptr2 << "\t\tptr1 = " << ptr1 << "\t\tratio = " << ratio<< endl;
        num++;
    } while ((ratio >= -3.23607) && (num < num_max));

    cout << "num = " << num << endl;
    int n = num + 2;
    vector<int> q(n);
    for (int f = 0; f < n; f++)
    {
        q[f] = ptr2;
        ptr3 = ptr1 + ptr2;
        ptr2 = ptr1;
        ptr1 = ptr3;
    }
    cout << "Fibonacci series in direct order:\n";
    for (auto j : q) 
    {
        cout << j << " ";
    }
    cout << endl;
}
相关问题