# C中的斐波那契数

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