反向斐波那契数列

Reversed Fibonacci Sequence

本文关键字:数列      更新时间:2023-10-16

我被分配了一个问题,在这个问题中,我必须创建一个反向斐波那契数列。当比率为-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;
}

代码中存在几个问题。 例如,在计算中(*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 << "ttptr2 = " << ptr2 << "ttptr1 = " << ptr1 << "ttratio = " << 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;
}