您的位置:首页 > 其它

文章标题

2017-08-08 09:11 162 查看

求第n个斐波那契数(随机输入一个数)

第一种,用递归求第n个斐波那契数(此种方法不适用于n特别大,因为n特别大的话,会因为每次的调用而耗费很多时间,计算机不会很快的算出来)


#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
int fib(int n)
{
if (n <= 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
int main()
{
int n = 0;
printf("n:");
scanf("%d", &n);
printf("%d\n", fib(n));
system("pause");
return 0;
}


第二种,用循环求第n个斐波那契数


#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
int fib(int n)
{
int a = 1;
int b = 1;
int c = 1;
if (n <= 2)
{
return 1;
}
else
{
while (n > 2)
{
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
}
int main()
{
int n = 0;
printf("n:");
scanf("%d", &n);
printf("%d\n", fib(n));
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: