从斐波那契序列 c++ 中的数组中查找正确的元素时出错

Error in finding the right elements from an array in fibonacci sequence c++

本文关键字:查找 元素 出错 数组 c++      更新时间:2023-10-16

所以我稍微改变了代码。它仍然不起作用,但我认为我更接近一点。程序应该检查你输入的数字(在柱[100]内(是否与斐波那契数字(存储在fib[30]中(匹配,然后打印匹配的数字。

#include <iostream>
#include <math.h>
using namespace std;
int main() {
long x, bar[100], fib[30];
cout << "Cate numere sunt in array? = ";
cin >> x;
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
fib[0] = 1;
fib[1] = 1;
fib[2] = 2;
for (int i = 3; i <= 30; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
//  cout << fib[i] << " ";
}
for (int i = 0; i < x; i++) {
bool fibonacci = false;
int j = 0;
while (j < 30  && !fib) {
// the mistake is here ( ' || ' instead of ' && ')
if (fib[j] == bar[i]) {
fibonacci = true;
}
j++;
}
if (fibonacci) {
cout << bar[i] << " ";
}
}

return 0;
}```

上面的代码对我来说效果很好。它打印出您在 bar[100] 数组中引入的斐波那契数列的每个正确数字。特别感谢@PaulMcKenzie和所有帮助过的人!

将 bar[1] bar[2] 和 bar[3] 初始化移到 for 循环之外。它们不是在其范围之外定义的。