最近没怎么看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;
}