gpt4 book ai didi

c++ - 打印斐波那契序列

转载 作者:行者123 更新时间:2023-12-02 09:55:28 25 4
gpt4 key购买 nike

我在用fibonacci系列打印矩阵时遇到麻烦。
当我启动程序时,它会打印一个带有整数和其余零的序列。我想得出一个结论。

顺序打印功能:

void printArray(int _A[], int _sz)
{
_A = new int(_sz);


cout << ">>> [ ";
for (int i = 0; i <= _sz; i++)
{
cout << _A[i] << " ";
}
cout << " ]\n";

}

计算序列的函数:
int fib(int _limit, int *_A)
{
int count = 0;
int fib0 = 1;
int fib1 = 1;
int fib2 = 0;
while (fib2 < _limit)
{
fib2 = fib0 + fib1;

count++;

fib0 = fib1;
fib1 = fib2;
}

_A = new int(count);
for (int i = 0; i < count; i++)
{
cout << _A[i] << " ";
}

return count;
}

主要:
int main()
{
int L;
int *A = nullptr;
cout << ">>> Press number: "
cin >> L;

if (L >= 0)
{
auto sz = fib(L, A);
cout << ">>> The Fibonacci series up to " << L << " is: \n";
printArray(A, sz); .
}
else
cout << ">>> Sorry, only positive integers accepted. Aborting...\n";
}

最佳答案

您有许多问题。

printArray中,您使用单个整数指针_A = new int(_sz);覆盖了传入的数组,尝试打印数组的所有元素将是未定义的行为。

fib中,您还可以使用new int(count);,这再次分配了一个指针而不是数组。您应该改为使用new int[count];。您永远不会将值分配给_A数组的元素,因此它们不会被初始化,并且使用它们是不确定的行为。

您不会将_A数组传递回调用函数。您可以通过将fib的声明更改为以下内容来解决此问题:

int fib(int _limit, int *&_A)

解决所有这些问题的一种好方法是使用 std::vector而不是数组,那么您无需预先计算序列的大小:
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::vector;

void printArray(const std::vector<int>& A)
{
cout << ">>> [ ";
for (int i : A)
{
cout << i << " ";
}
cout << " ]\n";

}

void fib(int _limit, std::vector<int>& A)
{
int fib0 = 1;
A.push_back(fib0);
int fib1 = 1;
int fib2 = 0;
while (fib2 < _limit)
{
A.push_back(fib1);
fib2 = fib0 + fib1;

fib0 = fib1;
fib1 = fib2;
}
}

int main()
{
int L;
std::vector<int> A;
cout << ">>> Press number: ";
cin >> L;

if (L >= 0)
{
fib(L, A);
cout << ">>> The Fibonacci series up to " << L << " is: \n";
printArray(A);
}
else
cout << ">>> Sorry, only positive integers accepted. Aborting...\n";
}

如果您正在学习一些反常的计算机科学类(class),这些类(class)在教您c++但又不允许您使用c++类,那么使用数组的相同代码可能如下所示:
#include <iostream>
using std::cout;
using std::cin;

void printArray(int A[], int _sz)
{
cout << ">>> [ ";
for (int i = 0; i <= _sz; i++)
{
cout << A[i] << " ";
}
cout << " ]\n";

}

int fib(int _limit, int *A)
{
int count = 0;
int fib0 = 1;
if (A) A[0] = fib0;
int fib1 = 1;
int fib2 = 0;
while (fib2 < _limit)
{
count++;
if (A) A[count] = fib1;
fib2 = fib0 + fib1;
fib0 = fib1;
fib1 = fib2;
}
return count;
}

int main()
{
int L;
int *A = nullptr;
cout << ">>> Press number: ";
cin >> L;

if (L >= 0)
{
auto sz = fib(L, A);
A = new int[sz];
fib(L, A);
cout << ">>> The Fibonacci series up to " << L << " is: \n";
printArray(A, sz);
}
else
cout << ">>> Sorry, only positive integers accepted. Aborting...\n";
}

关于c++ - 打印斐波那契序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60511142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com