c primer plus自学笔记-2

最近没怎么看C,上次的问题纠缠了太久也没结论,下次找机会找人问问吧~
根据书中内容实验了一下应用递归思想运行斐波那契数列计算,同时还原了一个正常循环思想的版本。
没有什么特别的难点,就运行速度而言,则根本不在一个量级,递归状态下,超过40!的计算延迟就已经很夸张了,循环则毫无压力。

recursion:

#include <stdio.h>

unsigned long Fibonacci(unsigned int n);

int main(void)
{
	int n;

	printf("Please enter a number as ordinal numberi of the answer(enter q to quit):\n");
	while (scanf("%u", &n) == 1)
	{
		printf("This is the Fibonacci number at %u:%lu\n", n, Fibonacci(n));
		printf("Please enter next number(enter q to quit):\n");
	}
	printf("Bye!");

	getchar();
	return 0;
}

unsigned long Fibonacci(unsigned int n)
{
	if (n > 2)
		return Fibonacci(n - 1) + Fibonacci(n - 2);
	else
		return 1;
}

loop:

#include <stdio.h>

unsigned long Fibonacci(unsigned int n);

int main(void)
{
	int n;

	printf("Please enter a number as ordinal numberi of the answer(enter q to quit):\n");
	while (scanf("%u", &n) == 1)
	{
		printf("This is the Fibonacci number at %u:%lu\n", n, Fibonacci(n) > 0 ? Fibonacci(n) : 1);
		printf("Please enter next number(enter q to quit):\n");
	}
	printf("Bye!");

	getchar();
	return 0;
}

unsigned long Fibonacci(unsigned int n)
{
	int c, m, x, y;
	x = 0;
	y = 1;
	for (c = 1;c <= n; c++)
	{
		m = x;
		x = x + y;
		y = m;	
	}
	return x;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值