简体   繁体   English

从斐波那契数列 C++ 中的数组中找到正确的元素时出错

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

So i am changed the code a little bit.所以我稍微改变了代码。 It still doesn't work but i think i am little bit closer.它仍然不起作用,但我想我有点接近了。 The program should check if the number you put in (inside bar[100]) match the fibonacci numbers(stored in fib[30]) and then print the ones that match.程序应该检查您输入的数字(在 bar[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;
}```

The code above works pretty well for me.上面的代码对我来说效果很好。 It prints out every right number of the Fibonacci sequence you introduce in the bar[100] array.它打印出您在 bar[100] 数组中引入的斐波那契数列的每个正确数字。 Special thanks to @PaulMcKenzie and everyone who helped!特别感谢@PaulMcKenzie 和所有帮助过的人!

Move the bar[1] bar[2] and bar[3] initialization outside of the for loop.将 bar[1] bar[2] 和 bar[3] 初始化移到 for 循环之外。 They are not defined outside the scope of it.它们没有在它的范围之外定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM