我创建了一个整数数组,提示用户选择2个数字,我试图从这2个数字中返回斐波那契数列

#include <stdio.h>

int main ()
{
  int a, b;

  int nums[48];

  for (int i = 0; i < 47; i++)

    {
      printf ("Pick a number between 1 - 47\n");
      scanf ("%d", &a);

      printf ("Pick a number between 1 - 47\n");
      scanf ("%d", &b);

      if (a >= 47 || a <= 1)
    {
      printf ("Out of range pick another number between 1 - 47\n");
      scanf ("%d", &a);
    }

      if (b >= 47 || b <= 1)
    {
      printf ("Out of range pick another number between 1 - 47\n");
      scanf ("%d", &b);
    }

      nums[i] = a;
      nums[i + 1] = b;

      int c = a + b;

      printf ("The sequence is: %d\n", c);
    }
  return 0;
}


最多返回47个斐波那契数列

最佳答案

假设您所期望的,我已经修改了您的代码。如果您想递归该代码的版本,那也是可能的。请在下面发表评论。

int main ()
{
  int a, b;

  int nums[48];
    //input two numbers once
    printf ("Pick a number between 1 - 47\n");
    scanf ("%d", &a);

    printf ("Pick a number between 1 - 47\n");
    scanf ("%d", &b);

    if (a >= 47 || a <= 1)
    {
      printf ("Out of range pick another number between 1 - 47\n");
      scanf ("%d", &a);
    }

    if (b >= 47 || b <= 1)
    {
      printf ("Out of range pick another number between 1 - 47\n");
      scanf ("%d", &b);
    }

    nums[0] = a;
    nums[1] = b;

   //calculate the fibonnaci series
   for (int i = 2; i <= 47; i++)
   {
      nums[i] = nums[i-1] + nums[i-2];

   }
   //Then print the series
    print("Fibonnacci series for a = %d and b = %d is ", a, b);

    for(int i = 0; i <= 47; i++)
        print("%d ", nums[i]);
  return 0;
}

关于c - 我创建了一个整数数组,提示用户选择2个数字,我试图从这2个数字中返回斐波那契数列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54642275/

10-13 09:51