斐波那契数列迭代与递归.

#include<stdio.h>
//斐波那契数列:第n个数字是 第n-1个数字与第n-2个数字 之和。
//例:1 1 2 3 5 8 13 21 34 55......
int Fib1(int x)//递归
{
    
    
	if (x>2)
	{
    
    
		return Fib1(x - 1) + Fib1(x - 2);
	}
	return 1;
}

int Fib2(int x)//迭代
{
    
    
	int a = 1;
	int b = 1;
	int c = 1;
	while (x>2)
	{
    
    
		c = a + b;
		a = b;
		b = c;
		x--;
	}
	return c;
}

int main() {
    
    
	int n;
	scanf_s("%d", &n);
	int ret = Fib1(n);
	printf("%d\n", ret);
	ret = Fib2(n);
	printf("%d\n", ret);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45275802/article/details/112427662
今日推荐