C中的斐波那契数

我必须做这个程序,但我真的不明白该怎么做。 有人可以帮我解释一下吗?

这是我得到的一些笔记

该程序计算(两次)斐波那契数列的前十个数字。斐波那契数列是从数字1开始两次的自然数的无穷序列。然后两个连续数字的总和之后立即产生以下数字: 1,1,2,3,5,8,13,21,34,55 第一个程序变体使用for循环。

随后是带有while循环的变体。该循环具有运行条件(此处:i <10),这意味着只要满足该条件,该循环就会运行。如果不再满足此条件,则退出循环。

请看一下程序,并尝试了解两个循环变体。

然后,请展开程序,以便用户可以选择要输出的斐波那契数(“请输入数字:”)。

请不要更改文本,否则自动检查将无法进行。

P. S。:由于值的范围是“ int”,因此只有最大为46的条目才会产生有意义的输出。

码:

#include <stdio.h>

int main(void) 
{
  int i, fib1, fib2, fib3;
  printf("This program calculates Fibonacci numbers\n\n");

// "Please enter the number:"

  printf("\nSolution using the for loop:\n");
  printf("1, 1");   //The first two numbers are printed outside the loop
  fib1=1; // 1. Fibonacci-number by Definition 1
  fib2=1; // 2. Fibonacci-number by Definition 1

  for(i=2; i<10; i++)  // Start with 2, since two numbers have already been issued
  {
    fib3=fib1+fib2;  // The next Fibonacci number is the sum of the two previous ones
    printf(", %d", fib3); // Output of the new Fibonacci number
    fib1=fib2;  // For the next round, the previous 2nd number becomes the 1st
    fib2=fib3;  // For the next round, the newly calculated number becomes the 2nd
  }

  printf("\n\nSolution using the while loop:\n");
  printf("1, 1");   // The first two numbers are printed outside the loop
  fib1=1; // 1. Fibonacci-number by Definition 1
  fib2=1; // 2. Fibonacci-number by Definition 1

  i=2; // Start with 2, since two numbers have already been issued
  while(i<10) // The running condition is in parentheses in the while loop
  {
    fib3=fib1+fib2;  // The next Fibonacci number is the sum of the two previous ones
    printf(", %d", fib3); // Output of the new Fibonacci number
    fib1=fib2;  // For the next round, the previous 2nd number becomes the 1st
    fib2=fib3;  // For the next round, the newly calculated number becomes the 2nd
    i++;  // For the next run, the loop counter must be increased by one
  }

  printf("\n\n");
  return 0;
}
评论