面向对象的C++程序设计 第六版 课后习题答案 第十四章.docx
- 文档编号:24161994
- 上传时间:2023-05-24
- 格式:DOCX
- 页数:32
- 大小:28.12KB
面向对象的C++程序设计 第六版 课后习题答案 第十四章.docx
《面向对象的C++程序设计 第六版 课后习题答案 第十四章.docx》由会员分享,可在线阅读,更多相关《面向对象的C++程序设计 第六版 课后习题答案 第十四章.docx(32页珍藏版)》请在冰豆网上搜索。
面向对象的C++程序设计第六版课后习题答案第十四章
Chapter14
RECURSION
1.SolutionstoandRemarksonSelectedProgrammingAssignments
1.FibonacciNumbers
ThesesolutionshavebeentestedundertwoLinuxversionsusingtwoversionsofg++,underWindowsXPwithVC++6.0andBorland5.0.Thefullrecursiveversionisslow.Ittakesabout17secondsfor1computationofFib1(35)onanolder,veryslowmachine(i486DX2/100,16MBRAM).Onamachinethatisclosertostate-of-theart(1GHzAthlon.266MHzfrontsidebus,512MBDDRRAM,fastdiskdrives)itrunsabitfaster:
N=35takes3seconds,N=40takesabout30seconds,N=41about50seconds,andN=42takes80seconds.AvalueofNgreaterthan47resultsinintegeroverflowandincorrectresultswithallthecompilersmentionedabove.
Withmostimplementations,longintisatypethesamesizeasint.Becausethereareafewimplementationsthatprovidealongintthatislongerthananint,Iusedlongastheargumentandreturntypesforthefibfunction.
TogetFibonaccinumbersuptoN=50forcheckingtheresultsoftheprogram,Ichangedthelongtypeintherecursivefunctiontolonglong(a19digitintegertypesupportedbyGNUg++,butnotANSI/ISOC++).Icompiledthisusingg++-3.0undertheDebianLinux3.0operatingsystemonaK6-2/350witha100MHzbackplaneand400KRAM.Onthissomewhatslowmachine,thisversionoftheprogramtookabouttwohoursforN==50,givingpresumablycorrectresults.(IacknowledgethatIdidnotlookthemup.)TheresultsagreewiththecodewithalongreturnandlongparametertypeuptoN=47.
ThisfunctioncomputesanddiscardstoomanyoftheFibonaccinumbers.Thiskindofrecursioniscalled'umbrellarecursion'becauseitspreadslikeanumbrella,recomputingvaluesmanytimes.
//File:
ch14prg1Fibonacci.cc
//Chapter14,ProgrammingProblem#1
//Writearecursivefunctionforafunctionhavingone
//parameterthatgeneratesthenthFibonaccinumber.
#include
#include
//Thisisthefullrecursiveversion.
unsignedlongFib1(intn)
{
if(n==0||n==1)
return1;
returnFib1(n-1)+Fib1(n-2);
}
intmain()
{
usingnamespacestd;
charans;
intN;
do
{
cout<<"Iwilldisplayfibonaccinumbers0-N.\n";
cout<<"Enteranlimit,\n";
cin>>N;
for(inti=0;i cout< cout<<"Y/ytocontinue,anythingelsequits\n"; cin>>ans; }while('Y'==ans||'y'==ans); return0; } 2.RecursiveIndexofSmallest CAUTIONS: Pleasewarnthestudentthatnumber_usedisNOTthelargestindexused,ratheritisthenumberofelements. Thiswasmyhardest-to-find-errorincodingthis.IalsorecommendthatthestudentremovetheSortfunctionfromDisplay10-12.IncludingSortobscuresthebehavioroftheindex_of_smallest.Ihaditfindingthemaximum,butIdidn'tspotthatuntilIremovedthesortroutineanditssupportroutines. Thisismodifiedfromcodeofthetext.Ipreferthatthestudentnotreinventthewheel: use.Sheshouldreusecodefromthetext'sDisplaystoadvantage! //file: ch14prg2.cc //Teststheprocedurerecursivefunctionindex_of_smallest //Sortroutineremovedtosimplifythetestingenvironment. #include voidfill_array(inta[],intsize,int&number_used); //Precondition: sizeisthedeclaredsizeofthearraya. //Postcondition: number_usedisthenumberofvaluesstored //ina[0]througha[number_used-1]havebeenfilledwith //nonnegativeintegersreadfromthekeyboard. intindex_of_smallest(constinta[], intstart_index,intnumber_used); //NOTE: designandimplementationofthisfunctionareat //theendofthisfile. //Precondition: 0<=start_index //Referencedarrayelementshavevalues. //Returnvalueistheindexisuchthata[i]isthesmallest //ofthevalues //a[start_index],a[start_index+1],...,a[number_used-1]. intmain() { usingnamespacestd; cout<<"Thisprogramtestsrecursivefunction" <<"index_of_smallest"< intsample_array[10],number_used; fill_array(sample_array,10,number_used); inti=index_of_smallest(sample_array,0,number_used); cout<<"Thenumberofelementsis" < cout<<"FortheminimumelementinthearrayINDEX=" < cout<<"Thearrayelementis"< < cout<<"Theelementsinthearrayare: \n"; for(intindex=0;index cout< cout< return0; } //Usesiostream voidfill_array(inta[],intsize,int&number_used) { usingnamespacestd; cout<<"Enterupto"< <<"nonnegativewholenumbers.\n" <<"Marktheendofthelistwith" <<"anegativenumber.\n"; intnext,index=0; cin>>next; while((next>=0)&&(index { a[index]=next; index++; cin>>next; } number_used=index; } RecursiveFunctionIndex_of_Smallest Thisrecursivefunctionreturnstheindexoftheminimumelementinthearraysegmentbetweenstart_indexandnumber_used. NonrecursiveCase: Ifwehaveonlyoneelementinasubarraywherestart_indexhasthevaluenumber_usedthenthatelementistheminimum,andstart_indexistheindexwewant. RecursiveCase: Ifthereismorethanoneelement,taketheelementwithsmallestindexandcompareitsvaluetotheminimumvalueofthearrayelementatindexreturnedbythefunctionoperatingontherestofthearray. intindex_of_smallest(constinta[],intstart_index,intnumber_used) { if(start_index==number_used-1) returnstart_index; intmin=a[start_index]; intindex_of_min= index_of_smallest(a,start_index+1,number_used); if(min>a[index_of_min]) returnindex_of_min; else returnstart_index; } Atypicalrun: Thisprogramtestsrecursivefunctionindex_of_smallest Enterupto10nonnegativewholenumbers. Marktheendofthelistwithanegativenumber. 435603-1 Thenumberofelementsis6 FortheminimumelementinthearrayINDEX=4 Thearrayelementis0 Theelementsinthearrayare: 435603 Anothertestrun: Thisprogramtestsrecursivefunctionindex_of_smallest Enterupto10nonnegativewholenumbers. Marktheendofthelistwithanegativenumber. 9238456329-1 Thenumberofelementsis10 FortheminimumelementinthearrayINDEX=1 Thearrayelementis2 Theelementsinthearrayare: 9238456329 3.NoSolutionProvided. 4.BinomialCoefficients. Writearecursivefunctionthatusesthegivenrecursiveformulatocalculatebinomialcoefficients.Test. Asecondpartgivesaconventionalformulaforthefactorial,instructsthestudenttodiscoverarecursiveversionsandtowritearecursivefunctionforthefactorial.Test. Notesonlyonthisproblem.ThestudentsshouldhaveseenthePascalTriangleinmathematicscoursesbythistime.Ifnot,suggestittothem.Idoitthisway: (x+y)1=1*x+1*y (x+y)2=1*x2+2*x*y+2*y2 (x+y)3=1*x3+3*x2*y1+3*x1*y2+y3 (x+y)4=1*x4+4*x3*y1+6*x2*y2+4*x1*y3+y4 (x+y)5=1*x5+5*x4*y1+10*x3*y2+10*x2*y3+5*x1*y4+x5 Wherethecoefficientsare 11 121 1331 14641 15101051 Thecoefficients,whenrearrangedare: 11 121 1331 14641 15101051 ThenweidentifytherowswithC(n,r)wherethenisthesecondentryinanyrow,andristhecolumnofthatrow,startingwith0: C(1,0)C(1,1) C(2,0)C(2,1)C(2,2) C(3,0)C(3,1)C(3,2)C(3,3) C(4,0)C(4,1)C(4,2)C(4,3)C(4,4) C(5,0)C(5,1)C(5,2)C(5,3)C(5,4)C(5,5) Prodthestudentsalittle.Theywillseethataddinganytworowitemsgivesthevaluedirectlyundertheseconditem.Thereistherecursionrelationtheyneed: C(n,r)+C(n,r+1)=C(n+1,r+1) Thisisanotherumbrellarecursion,similarinthisrespecttoProgrammingproblem#1.Ittakesconsiderabletimeandspacetodothiswithrecursion. Ifbinomialcoefficientsarereallyneeded,abunchofthemarelikelyneeded.Itisbettertouseasolutionwhereallthecoefficientsuptothoseneededarecomputedandstored(insomeglobalarray,oritcouldbearrangedforthefunctiontoreturnacurrentlyavailablevalue,orifitisnotavailable,tocomputeallbinomialcoefficientsuptotheonedesired.(Thisisagoodplacefortheideasofa"dynamicarray"ora"source"class.) 5.RecursiveReverseArraySegment. Theproblemistorecursivelyreverseanarraysegment.Thefunctiontakesanarrayargumentandtwointegerargumentsthatspecifythestartandtheendofthesegmentofthearraytobereversed. voidrecursive_reverse(inta[],intstart,intend); Thetaskissplitintotwopieces: NonRecursive: Hereifthereisonlyoneelement,wearedoneoriftherearetwoelements,wecanjustswapthem,andwearedone. Recursive: Reversethestartandendelements.Arecursivecallismadetothefunctiontofinishthejob: recursive_reverse(a,start+1,end-1); Housekeeping: Howdoweknowifthereisonlyoneelement? Howdoweknowwehaveonlytwoelements? Ifthereisanoddnumberofarrayelementstobeswapped,wetakecareoftwoattime.Wewindupwithonearrayelementforthenon-recursivecasetodealwith.Thenwecantest start==end. Howdoyouknowthereareonlytwoelementstobeswapped? Ifstart+1==end,thenthereonlytwoelements.Weswapthemandquit. Recursivecase: Ifthereisanevennumberofarrayelementstobeswapped,allofthemwillbedealtwithintherecursivecase.Therewillbeonelastrecursivecallmadewithanarrayoftwoelements(start+1==end).Inthiscall,thislastpairwillbeswapped.Therewillbeonelastrecursivecallwithstartargumentstart+1+1andendargumentend-1.Thismakesthevaluesofstartandendinthenextrecurs
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 面向对象的C+程序设计 第六版 课后习题答案 第十四章 面向 对象 C+ 程序设计 第六 课后 习题 答案 第十四