Fibonacci sequence while loop

旧巷老猫 提交于 2019-12-13 08:47:02

问题


I have to write code that displays the Fibonacci sequence to the user desired number of terms and must also use a while loop. I'm not sure why this code isn't working.

#include <stdio.h>
#include <stdlib.h>
int main (void) {
    int max;
    printf("Enter the max term of the Fibonacci Sequence:\n");
    scanf("%i", &max);
    int a=0;
    int b=0;
    a=2;

    while(a<max) {
        if((a==0||a==1))
        {
            printf("%i\n", &a);
            ++a;
        }
        else if(a>1)
        {
            a=(a-1)+(a-2);
            printf("%i\n", &a);
            ++a;
        }
    }
    return 0;
}

回答1:


You can try this.

#include <stdio.h>
#include <stdlib.h>
int main (void) {
   int max;
   printf("Enter the max term of the Fibonacci Sequence:\n");
   scanf("%i", &max);
   int n=0;
   int a=0;
   int b=1;
   int next;

   while(n<max) {
      if ( n <= 1 )
        {
          next = n;
          n++;
        }
      else
       {
         next = a + b;
         a = b;
         b = next;
         n++;
       }
    printf("%d\n",next);
}
return 0;

}

issues with your code:

  1. you are initialising a=2 => it won't take first if loop -- '0' will not be printed in your result.
  2. a=(a-1)+(a-2); i.e a = 1 then you are doing ++a; => a == 2. thus it again else loop with same a==2.

hence it will print the same value and loop executes infinitely.




回答2:


In the very beginning of your program (before the while loop) a is 2 (see the line a=2).

And in the while loop you do following:

a=(a-1)+(a-2); // a = 2-1+2-2 i.e. a = 1

and right after it

++a; // a == 2

So, after it a==2 again. This loop never ends.

But it is technical problem. More important is that you are trying to calculate not Fibonacci Sequence. In the Fibonacci Sequence each subsequent number is the sum of the previous two. But in your code there is adding of not two previous numbers of Fibonacci Sequence, but previous two Natural numbers.

You have variable b, because someone told you to add it. And it was right! Just remember previous found element of the Fibonacci Sequence in b. When you know previous one element and current one, it is possible to calculate next one.



来源:https://stackoverflow.com/questions/35401864/fibonacci-sequence-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!