[英]Error in finding the right elements from an array in fibonacci sequence c++
所以我稍微改變了代碼。 它仍然不起作用,但我想我有點接近了。 程序應該檢查您輸入的數字(在 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;
}```
上面的代碼對我來說效果很好。 它打印出您在 bar[100] 數組中引入的斐波那契數列的每個正確數字。 特別感謝@PaulMcKenzie 和所有幫助過的人!
將 bar[1] bar[2] 和 bar[3] 初始化移到 for 循環之外。 它們沒有在它的范圍之外定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.