首页 C++程序设计 - 第05讲

C++程序设计 - 第05讲

举报
开通vip

C++程序设计 - 第05讲C++程序设计西北工业大学软件与微电子学院杨帆Part2:ControlStatements,MethodsandArrays Chapter4:ControlStatements Chapter5:FunctionsandanIntrotoRecursion Chapter6:ArraysandVectors Chapter7:PointersChapter5:FunctionsandanIntrotoRecursion divideandconquer(分而治之)developandmaintainalarge...

C++程序设计 - 第05讲
C++程序 设计 领导形象设计圆作业设计ao工艺污水处理厂设计附属工程施工组织设计清扫机器人结构设计 西北工业大学软件与微电子学院杨帆Part2:ControlStatements,MethodsandArrays Chapter4:ControlStatements Chapter5:FunctionsandanIntrotoRecursion Chapter6:ArraysandVectors Chapter7:PointersChapter5:FunctionsandanIntrotoRecursion divideandconquer(分而治之)developandmaintainalargeprogramistoconstructitfromsmall,simplepieces,orcomponents.ProgramComponentsinC++ C++programsaretypicallywrittenbycombiningnewfunctionsandclassesyouwritewith“prepackaged”functionsandclassesavailableintheC++StandardLibrary. Functionsyouwritearereferredtoasuser-definedfunctionsorprogrammer-definedfunctions. Themotivationsformodularizingaprogramwithfunctions: divide-and-conquerapproach softwarereuse toavoidrepeatingcode makestheprogrameasiertodebugandmaintain afunctionisinvokedbyafunctioncall,andwhenthecalledfunctioncompletesitstask,iteitherreturnsaresultorsimplyreturnscontroltothecaller.GlobalFunctions Sometimesfunctions,suchasmain,arenotmembersofaclass.Suchfunctionsarecalledglobalfunctions. Likeaclass’smemberfunctions,thefunctionprototypesforglobalfunctionsareplacedinheaders,sothattheglobalfunctionscanbereusedinanyprogramthatincludestheheaderandthatcanlinktothefunction’sobjectcode.MathLibraryFunctions The<cmath>headerprovidesacollectionoffunctionsthatenableyoutoperformcommonmathematicalcalculations. sqrt(900.0); Functionargumentsmaybeconstants,variablesormorecomplexexpressions. cout<<sqrt(c+d*f)<<endl;FunctionPrototypes Afunctionprototype“函数原型”(alsocalledafunctiondeclaration“函数声明”)tellsthecompilerthenameofafunction,thetypeofdataitreturns,thenumberofparametersitexpectstoreceive,thetypesofthoseparametersandtheorderinwhichtheparametersofthosetypesareexpected.intmaximum(int,int,int);FunctionSignatures Theportionofafunctionprototypethatincludesthenameofthefunctionandthetypesofitsargumentsiscalledthefunctionsignature. Thefunctionsignaturedoesnotspecifythefunction’sreturntype. Functionsinthesamescopemusthaveuniquesignatures.FunctionReturnValueintmaximum(int,int,int);intx=maximum(3,5,9);voidmaximum(int,int,int);cout<<maximum(5,4,0);intmaximum(intx,inty,intz){intmaximumValue=x;if(y>maximumValue)maximumValue=y;if(z>maximumValue)maximumValue=z;returnmaximumValue;}intmain(){inta,b,c,d;a=b=c=d=0;d=maximum(a,b,c);}05-01.cppintmaximum(intx,inty,intz)d=maximum(a,b,c); formalparametervs.actualparameter Therearethreewaystoreturncontroltothepointatwhichafunctionwasinvoked. Ifthefunctiondoesnotreturnaresult(i.e.,ithasavoidreturntype),controlreturnswhentheprogramreachesthefunction-endingrightbrace,orbyexecutionofthestatement“return;” Ifthefunctiondoesreturnaresult,thestatement“returnexpression;”evaluatesexpressionandreturnsthevalueofexpressiontothecaller.ArgumentCoercion Animportantfeatureoffunctionprototypesisargumentcoercion(“参数转换”)—i.e.,forcingargumentstotheappropriatetypesspecifiedbytheparameterdeclarations. voidTest(doublea); Test(3);ArgumentPromotionRules Sometimes,argumentvaluesthatdonotcorrespondpreciselytotheparametertypesinthefunctionprototypecanbeconvertedbythecompilertothepropertypebeforethefunctioniscalled. TheseconversionsoccurasspecifiedbyC++’spromotionrules. thefundamentaldatatypesinorderfrom“highesttype”to“lowesttype.” Convertingvaluestolowerfundamentaltypescanresultinincorrectvalues. Functionargumentvaluesareconvertedtotheparametertypesinafunctionprototypeasiftheywerebeingassigneddirectlytovariablesofthosetypes. square(4.5)returns16,not20.25 RandomNumberGeneration usingtheC++StandardLibraryfunctionrand05-02.cpp05-03.cpp05-04.cpphttp://www.cnblogs.com/afarmer/archive/2011/05/01/2033715.htmlC/C++中产生随机数(rand,srand用法)实验06:函数初步与随机数阅读Self-ReviewExercisesandAnswers(6.1~6.10)必做题WriteafunctionintegerPower(base,exponent)thatreturnsthevalueofbaseexponent.Forexample,integerPower(3,4)=3*3*3*3.Assumethatexponentisapositive,nonzerointegerandthatbaseisaninteger.Donotuseanymathlibraryfunctions.Writeaprogramthatplaysthegameof“guessthenumber”asfollows:Yourprogramchoosesthenumbertobeguessedbyselectinganintegeratrandomintherange1to1000.Theprogramthendisplaysthefollowing:Ihaveanumberbetween1and1000.Canyouguessmynumber?Pleasetypeyourfirstguess.Theplayerthentypesafirstguess.Theprogramrespondswithoneofthefollowing:1.Excellent!Youguessedthenumber!Wouldyouliketoplayagain(yorn)?2.Toolow.Tryagain.3.Toohigh.Tryagain.Iftheplayer’sguessisincorrect,yourprogramshouldloopuntiltheplayerfinallygetsthenumberright.YourprogramshouldkeeptellingtheplayerToohighorToolowtohelptheplayer“zeroin”onthecorrectanswer. 实验作业要求: 当次实验课结束前务必提交实验作业 实验作业要求压缩打包,压缩文件命名方式为:“学号姓名.rar”,例如“2013303281刘怡芸.rar” 将实验作业提交给实验课老师Introducingenum Anenumeration,introducedbythekeywordenumandfollowedbyatypename(inthiscase,Status),isasetofintegerconstantsrepresentedbyidentifiers. Thevaluesoftheseenumerationconstantsstartat0,unlessspecifiedotherwise,andincrementby1. AnotherpopularenumerationisenumMonths{JAN=1,FEB,MAR,APR,MAY,JUN,JUL=0,AUG,SEP,OCT,NOV,DEC}; whichcreatesuser-definedtypeMonthswithenumerationconstantsrepresentingthemonthsoftheyear.Thefirstvalueintheprecedingenumerationisexplicitlysetto1,sotheremainingvaluesincrementfrom1,resultinginthevalues1through12. Anyenumerationconstantcanbeassignedanintegervalueintheenumerationdefinition,andsubsequentenumerationconstantseachhaveavalue1higherthantheprecedingconstantinthelistuntilthenextexplicitsetting.05-05.cppFunctionswithEmptyParameterLists InC++,anemptyparameterlistisspecifiedbywritingeithervoidornothingatallinparentheses. Theprototypespecifiesthatfunctionprintdoesnottakeargumentsanddoesnotreturnavalue. voidprint(); intprint(void);DefaultArguments It’scommonforaprogramtoinvokeafunctionrepeatedlywiththesameargumentvalueforaparticularparameter.Insuchcases,youcanspecifythatsuchaparameterhasadefaultargument,i.e.,adefaultvaluetobepassedtothatparameter. mustbetherightmost(trailing)arguments mustbespecifiedwiththefirstoccurrenceofthefunctionname—typically,inthefunctionprototype canbeanyexpression,includingconstants,variablesorfunctioncalls05-06.cppFunctionCallStack StackandQueue(栈与队列) Stacksareknownaslast-in,first-out(LIFO)datastructures—thelastitempushed(inserted)onthestackisthefirstitempopped(removed)fromthestack. Queues—first-in,first-out(FIFO)05-07.cppInlineFunctions Placingthequalifierinlinebeforeafunction’sreturntypeinthefunctiondefinition“advises”thecompilertogenerateacopyofthefunction’sbodycodeinplace(whenappropriate)toavoidafunctioncall. Thecompilercanignoretheinlinequalifierandtypicallydoessoforallbutthesmallestfunctions.inlinedoublecube(constdoubleside){returnside*side*side;}intmain(){doublesideValue;cout<<"Enterthesidelengthofyourcube:";cin>>sideValue;cout<<"Volumeofcubewithside"<<sideValue<<"is"<<cube(sideValue)<<endl;}FunctionOverloading C++enablesseveralfunctionsofthesamenametobedefined,aslongastheyhavedifferentsignatures. Thisiscalledfunctionoverloading. Functionoverloadingisusedtocreateseveralfunctionsofthesamenamethatperformsimilartasks,butondifferentdatatypes.__Z6squrei__Z6squred_main05-08.cpp Overloadedfunctionscanhavedifferentreturntypes,butiftheydo,theymustalsohavedifferentparameterlists. Again,youcannothavetwofunctionswiththesamesignatureanddifferentreturntypes. voidf(); intf(); inti=f(); f(); functionmainiscannotbeoverloaded.voidS();voidS(int);voidS(double,double=1.2);voidMax(double);intmain(){ S(2.4); return0;}Recursion(递归) Arecursivefunctionisafunctionthatcallsitself,eitherdirectly,orindirectly(throughanotherfunction). n!=n×(n-1)×(n-2)×…×1 factorial=1; for(intcounter=number;counter>=1;--counter) factorial*=counter; n!=n×(n-1)!05-09.cpp FibonacciSeries 0,1,1,2,3,5,8,13,21,… fibonacci(0)=0 fibonacci(1)=1 fibonacci(n)=fibonacci(n–1)+fibonacci(n–2)05-10.cpp Recursionvs.Iteration Recursionhasnegatives.Itrepeatedlyinvokesthemechanism,andconsequentlytheoverhead,offunctioncalls.Thiscanbeexpensiveinbothprocessortimeandmemoryspace. Eachrecursivecallcausesanothercopyofthefunction(actuallyonlythefunction’svariables)tobecreated;thiscanconsumeconsiderablememory. Iterationnormallyoccurswithinafunction,sotheoverheadofrepeatedfunctioncallsandextramemoryassignmentisomitted.实验07:递归函数必做题Writearecursivefunctionpower(base,exponent)that,wheninvoked,returnsbaseexponent. Forexample,power(3,4)=3*3*3*3.Assumethat exponentisanintegergreaterthanorequalto1. Hint:Therecursionstepwouldusetherelationship baseexponent=base×baseexponent–1andtheterminating conditionoccurswhenexponentisequalto1,because base1=base.Thegreatestcommondivisorofintegersxandyisthelargestintegerthatevenlydividesbothxandy.Writearecursivefunctiongcdthatreturnsthegreatestcommondivisorofxandy,definedrecursivelyasfollows:Ifyisequalto0,thengcd(x,y)isx;otherwise,gcd(x,y)isgcd(y,x%y),where%isthemodulusoperator. [Note:Forthisalgorithm,xmustbelargerthany.]选做题了解研究“汉诺塔问题”,假设移动一片黄金圆盘需要1秒钟,设计算法并编写程序计算移动64片黄金圆盘所需的时间。http://blog.csdn.net/geekwangminli/article/details/7981570 实验作业要求: 当次实验课结束前务必提交实验作业 实验作业要求压缩打包,压缩文件命名方式为:“学号姓名.rar”,例如“2013303281刘怡芸.rar” 将实验作业提交给实验课老师
本文档为【C++程序设计 - 第05讲】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_801591
暂无简介~
格式:ppt
大小:1MB
软件:PowerPoint
页数:0
分类:互联网
上传时间:2019-03-31
浏览量:23