系列文章目录
前言
《数据结构基础》c语言版 第2版,Ellis Horowitz著,朱仲涛译
1.3节,page14,习题8
一、题目描述
fibonacci数定义为:f0=0,f1=1,以及当i>1时,fi=fi-1+fi-2.写出计算fi的c语言递归函数和循环函数
二、c++代码
1.循环版
代码如下:
#include <iostream>
using namespace std;
int main()
{
int n;
printf("enter the number:\n");
scanf("%d",&n);
int f[1000];
f[0]=0;
f[1]=1;
for(int i=2;i<=n;i++)
{
f[i]=f[i-1]+f[i-2];
}
printf("the result for %d is:%d\n",n,f[n]);
}
2.递归版
代码如下:
#include <iostream>
using namespace std;
int fibonacci(int x)
{
if(x==0)
return 0;
else if(x==1)
return 1;
else
return fibonacci(x-1)+fibonacci(x-2);
}
int main()
{
int n;
printf("enter the number:\n");
scanf("%d",&n);
printf("the result for %d is:%d\n",n,fibonacci(n));
}
3.使用栈
代码如下:
#include<stack>
#include<iostream>
using namespace std;
typedef struct{
int value;//结点下标
int tag;//标志信息:1为左,2为右
}node;
int Fibnacci(int n)
{
int result=0;
stack<node> s;
node w;
do {
while (n>1)
{
w.value=n;
w.tag=1;
s.push(w);
n--;
}
result = result + n;
while (!s.empty())
{
w = s.top();
s.pop();
if(w.tag==1)
{
w.tag=2;
s.push(w);
n=w.value-2;
break;
}
}
}while (!s.empty());
return result;
}
int main()
{
printf("%d", Fibnacci(4));
return 0;
}