.递归和非递归分别实现求第n个斐波那契数。

思路:从第三个数字开始,每个数字的值等于它前两个数值之和。
#include<stdio.h>  
#include<windows.h>
int fib(int n)
{//递归实现
	if (n < 3)
	{
		return 1;
	}
	else
		return fib(n - 1) + fib(n - 2);
}
int fib(int n)
{//迭代实现
	int first = 1;
	int second = 1;
	int third = 1;
	while (n > 2)
	{
		third = first + second;
		first = second;
		second = third;
		n--;
	}
	return third;
}
int main()
{
	int i = 1;
	for (; i < 10; i++)
	{
		printf("%d\n", fib(i));
	}
	printf("\n");
	system("pause");
	return 0;
}

结果显示:


猜你喜欢

转载自blog.csdn.net/zy_20181010/article/details/80246149