我创建的int数组,系统将提示用户挑选2号,我想从这些数字2返回斐波那契序列

问题描述 投票:0回答:1

我创建的int数组,系统将提示用户挑选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号斐波那契序列

c arrays recursion fibonacci
1个回答
0
投票

我已修改了代码,假设你的期待是什么。如果你想这个代码的一个版本迭代的也是可能的。只是评论如下。

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.