递推语法讲解英语版

递推语法讲解英语版

ID:5841851

大小:56.50 KB

页数:3页

时间:2017-12-25

递推语法讲解英语版_第1页
递推语法讲解英语版_第2页
递推语法讲解英语版_第3页
资源描述:

《递推语法讲解英语版》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

1、8.4NestedCallandRecursion8.4.1NestedCallStartingfromthemainfunction,themainfunctioncallsfunctionf1(),functionf1()thencallsthefunctionf2(),functionf2()thencallsthefunctionf3(),andsoon.Thisdeparturefromthemainfunctiontoformalongcallchain,isknownasNestedCall.Fig.1show

2、sthewholeprocess.f2()Main()f1()④③②①Callf2;Follow-upstatement;Callf1();Follow-upstatement;⑤⑧⑦⑨⑥ReturnReturnEndFig.1.NestedCallNote:Cdoesnothavenesteddefinitionsthatareavailable(可用的)insomeotherprogramminglanguages.Example1:calculateareaofcirqueAnalyse:1.areaofcirque=

3、areaofoutercirque-areaofinnercirque.2.Definetwofunction:(1)circleArea:calculateareaofcircle;(2)ringArea:calculateareaofcirque.Program:#include#definePI3.14doublecircleArea(doubler)/*calculateareaofcircle*/{returnPI*r*r;}doubleringArea(doubler1,doubler2)/*c

4、alculateareaofcirque*/{if(r1<=r2)returncircleArea(r2)-circleArea(r1);elsereturncircleArea(r1)-circleArea(r2);}voidmain(){doubler1,r2,s;printf(“tInputr1,r2:”);scanf(“%lf%lf”,&r1,&r2);s=ringArea(r1,r2);/*callfunction*/printf("tTheareais:%.2lf“,s);}8.4.2Recursio

5、nCfunctionsmaybeusedrecursively;thatis,afunctionmaycallitselfeitherdirectlyorindirectly.Functionsarecalleddirectlyorindirectlythemselvsisknownasrecursion.Fig.2showstheprocessofRecursion.f1()Callf1()f1()Callf2()f1()Callf2()(a)Directlycallsitself(b)Indirectlycallsits

6、elfFig.2TheprocessofrecursionExample2:factorials(n!)Analyse:n!=n*(n-1)*(n-2)…2*1;n!=n*(n-1)!;(n-1)!=(n-1)*(n-2)!;(n-2)!=(n-2)*(n-3)!;…2!=2*1!;1!=1Program:#includelongfac(intn){longf;if(n==0

7、

8、n==1)f=1;elsef=n*fac(n-1);printf("t%d!=%ld",n,f);returnf;}void

9、main(){printf("t5!=%ld",fac(5));}Exercise8-4-1.Writeaprogramtoprintanumberasacharacterstringfromhigh-orderdigitstolow-orderdigits.Analyse:Wecanuserecursivesolutiontodealwiththisprobleminwhichprintdfirstcallsitselftocopewithanyleadingdigits,thenprintsthetrailin

10、gdigit.Again,thisversioncanfailonthelargestnegativenumber.Referenceprogram:#include/*printd:printnindecimal*/voidprintd(intn){if(n<0){pu

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。