2017-02-23 34 views
0

使用这个程序我可以很容易地得到斐波那契数列的序列。检查1到N之间有多少个斐波纳契数字存在

int main(){ 

int n,i,first=0,second=1,next=0,fib=0; 

// 0 1 1 2 3 5 8 13 21 34 

printf("Enter the value of N: "); 
scanf("%d",&n); 

for(i=1;i<=n;i++){ 


    next = first+second; 
    first = second; 
    second = next; 

    printf("%d",next); 


} 

}

可是如何才能让许多febonacci数字在那里。

例如,如果我输入35,则结果应该显示10个febonacci数字。

+2

这_Super easy_做。你想要计算这些数字,所以你需要另一个变量来做到这一点... – ForceBru

+0

试过这个,但没有工作: if(next == i) fib = fib + 1; – Tahmid

+0

https://oeis.org/A108852可能会帮助 – 2017-02-23 19:13:14

回答

0

这里的答案:

int main(){ 

    int n,i,first=0,second=1,next=0,fib=0; 

    // 0 1 1 2 3 5 8 13 21 34 

    printf("Enter the value of N: "); 
    scanf("%d",&n); 

    for(i=1;next<=n;i++){ 
     next = first+second; 
     first = second; 
     second = next; 
    } 
printf("%d",i); 

} 

由于VHS

+0

然后请“接受”该答案:有一个复选框让你表示感谢。 –

3

您的for循环正在运行n迭代次数,而不是运行,直到next超过n。请参阅下面的修订版本的代码:

int main(){ 

    int n,count=2,first=0,second=1,next=0,fib=0; 

    // 0 1 1 2 3 5 8 13 21 34 

    printf("Enter the value of N: "); 
    scanf("%d",&n); 

    while((first+second) <= n){  
     next = first+second; 
     first = second; 
     second = next;  
     printf("%d",next); 
     count++; 
    } 
    printf("found %d numbers ", count); 
} 
+0

但我不想要这个系列,我只想要那个系列有多少个数字。谢谢回复。 – Tahmid

+0

如果你不想要这个系列,注释掉printf(“%d”,next); ' – VHS

+0

让我清楚。如果我在程序中输入36,它会给我10,因为只有10斐波那契数在1和36之间。 – Tahmid