[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
题目:f(n)=f(n-1)+f(n-2)
f(0)=2; f(1)=3 ,求f(40)
这个题需要用到函数递归来计算,
我们已知 f(0)和 f(1),
那么通过计算, f(2)就是 f(0)+ f(1)= 2 + 3 = 5;
创造函数F,传入值是 int n,返回值是int;
static int F(int n) { }
在函数中直接返回公式:
return F(n - 1) + F(n - 2);//函数递归调用
这个时候需要有一个终止递归的条件,把 f(0)和 f(1)写上去;
if (n == 0) return 2; //终止递归的条件 if (n == 1) return 3;
在main函数中调用函数F,得到res值就是f(40)的值,作为对比算出f(2)的值:
static void Main(string[] args) { int res = F(40); int res2 = F(2); }
源代码如下:
using System; //02 //f(n)=f(n-1)+f(n-2) f(0)=2 f(1)=3 ,用程序求得f(40) namespace
_05s { class Program { static void Main(string[] args) { int res = F(40); int
res2 = F(2); Console.WriteLine("f40:" + res); Console.WriteLine("f2:" + res2);
} static int F(int n) { if (n == 0) return 2; //终止递归的条件 if (n == 1) return 3;
return F(n - 1) + F(n - 2);//函数递归调用 } } }
打印结果如下:
三连~