斐波那契序列while循环 [英] Fibonacci sequence while loop

查看:76
本文介绍了斐波那契序列while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写将斐波那契数列显示给用户所需数量的术语的代码,并且还必须使用while循环.我不确定为什么此代码无法正常工作.

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;
}

推荐答案

您可以尝试一下.

#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;
}

带有您的代码的问题:

  1. 遵循声明&初始化时,您设置 a = 2 =>不会使用 if 语句的 true分支-'0'不会显示在您的结果中.
  2. a =(a-1)+(a-2); a = 1 那么您正在执行 ++ a; => a == 2 .因此再次使用相同的 a == 2 再次 else 语句.
  1. following declaration & initialisation, you set a=2 => it won't take the true branch of the if statement -- '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 statement with same a==2.

因此它将打印相同的值并无限执行循环.

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

这篇关于斐波那契序列while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆