4.5.1简单递归消除
// DataStructTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream.h>
#include <malloc.h>
//递归方法
int Fib_1(int n)
{
if (n==0)
return 0;
else if (n==1)
return 1;
else
return Fib_1(n-1)+Fib_1(n-2);
}
//循环方法
int Fib_2(int n)
{
if (n==0)
return 0;
else
{
int x=0,y=1,z=0;
for(int i=2;i<=n;i++)
{
z=y;
y=x+y;
x=z;
}
return y;
}
}
int main(int argc, char* argv[])
{
cout<<"递方方法计算N=20的斐波那齐数列"<<Fib_1(20)<<endl;
//
cout<<"循环方法计算N=20的斐波那齐数列"<<Fib_2(20)<<endl;
//
return 0;
}
一点说明:为什么在标题中要嵌入英文?原因是为了能够让国外的网友能查询到这篇文章。平常在Google上查资料的时候,经常参考国外网友的博客,帮助我解决了很多问题,所以我也想让他们能够参考我写的内容。当然文中我不可能全部译为英文,所以我尽量把代码粘全,靠代码说话吧。



浙公网安备 33010602011771号