温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c/c++ 斐波那契数列 利用模板元解决递归慢的问题

发布时间:2020-05-21 11:53:35 来源:网络 阅读:1629 作者:超级极客 栏目:编程语言

#include<iostream>

//模板元 变成 一般用于递归 游戏开发里常用
template<int N>
struct data
{
 enum {res=data<N-1>::res+data<N-2>::res};
};
template<>
struct data<1>
{
 enum {res=1};
};
template<>
struct data<2>
{
 enum {res=2};
};


int getdata(int n)
{
 if (n==1||n==2)
 {
  return 1;
 }
 else
 {
  return  getdata(n - 1) + getdata(n - 2);
 }
}
void main()
{
 int i;
 int f[20] = { 1,1 };//20个数组,但它的序号是从0开始到19的...
 for (i = 2;i < 20;i++)
 {
  f[i] = f[i - 2] + f[i - 1];
  //std::cout<<f[i-1] << std::endl;
 }
 std::cout<<f[19]<<std::endl;
 int unm = data<45>::res;
 std::cout << unm << std::endl;
 //std::cout << getdata(40) << std::endl;


 std::cin.get();

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI