已阅读5页,还剩89页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Copyright2008PearsonAddison-Wesley.Allrightsreserved.,Chapter4,ProceduralAbstractionandFunctionsThatReturnaValue,Slide4-3,Overview,4.1Top-DownDesign4.2PredefinedFunctions4.3Programmer-DefinedFunctions4.4ProceduralAbstraction4.5LocalVariables4.6OverloadingFunctionNames,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,4.1,Top-DownDesign,Slide4-5,TopDownDesign,TowriteaprogramDevelopthealgorithmthattheprogramwilluseTranslatethealgorithmintotheprogramminglanguageTopDownDesign(alsocalledstepwiserefinement)BreakthealgorithmintosubtasksBreakeachsubtaskintosmallersubtasksEventuallythesmallersubtasksaretrivialtoimplementintheprogramminglanguage,Slide4-6,BenefitsofTopDownDesign,Subtasks,orfunctionsinC+,makeprogramsEasiertounderstandEasiertochangeEasiertowriteEasiertotestEasiertodebugEasierforteamstodevelop,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,4.2,PredefinedFunctions,Slide4-8,PredefinedFunctions,C+comeswithlibrariesofpredefinedfunctionsExample:sqrtfunctionthe_root=sqrt(9.0);returns,orcomputes,thesquarerootofanumberThenumber,9,iscalledtheargumentthe_rootwillcontain3.0,sqrt(9.0)isafunctioncallItinvokes,orsetsinaction,thesqrtfunctionTheargument(9),canalsobeavariableoranexpressionAfunctioncallcanbeusedlikeanyexpressionbonus=sqrt(sales)/10;Cout“Thesideofasquarewitharea“area“is“sqrt(area);,Slide4-9,Display4.1,FunctionCalls,Slide4-10,FunctionCallSyntax,Function_name(Argument_List)Argument_Listisacommaseparatedlist:(Argument_1,Argument_2,Argument_Last)Example:side=sqrt(area);cout“2.5tothepower3.0is“pow(2.5,3.0);,Slide4-11,FunctionLibraries,PredefinedfunctionsarefoundinlibrariesThelibrarymustbe“included”inaprogramtomakethefunctionsavailableAnincludedirectivetellsthecompilerwhichlibraryheaderfiletoinclude.Toincludethemathlibrarycontainingsqrt():#includeNewerstandardlibraries,suchascmath,alsorequirethedirectiveusingnamespacestd;,abs(x)-intvalue=abs(-8);ReturnsabsolutevalueofargumentxReturnvalueisoftypeintArgumentisoftypexFoundinthelibrarycstdlibfabs(x)-doublevalue=fabs(-8.0);ReturnstheabsolutevalueofargumentxReturnvalueisoftypedoubleArgumentisoftypedoubleFoundinthelibrarycmath,Slide4-12,Display4.2,OtherPredefinedFunctions,Slide4-13,TypeCasting,Recalltheproblemwithintegerdivision:inttotal_candy=9,number_of_people=4;doublecandy_per_person;candy_per_person=total_candy/number_of_people;candy_per_person=2,not2.25!ATypeCastproducesavalueofonetypefromanothertypestatic_cast(total_candy)producesadoublerepresentingtheintegervalueoftotal_candy,Slide4-14,Integerdivisionoccursbeforetypecast,TypeCastExample,inttotal_candy=9,number_of_people=4;doublecandy_per_person;candy_per_person=static_cast(total_candy)/number_of_people;candy_per_personnowis2.25!Thiswouldalsowork:candy_per_person=total_candy/static_cast(number_of_people);Thiswouldnot!candy_per_person=static_cast(total_candy/number_of_people);,Slide4-15,OldStyleTypeCast,C+isanevolvinglanguageThisoldermethodoftypecastingmaybediscontinuedinfutureversionsofC+candy_per_person=double(total_candy)/number_of_people;,Slide4-16,Section4.2Conclusion,CanyouDeterminethevalueofd?doubled=11/2;Determinethevalueofpow(2,3)fabs(-3.5)sqrt(pow(3,2)7/abs(-2)ceil(5.8)floor(5.8)ConvertthefollowingtoC+,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,4.3,Programmer-DefinedFunctions,TwocomponentsofafunctiondefinitionFunctiondeclaration(orfunctionprototype)ShowshowthefunctioniscalledMustappearinthecodebeforethefunctioncanbecalledSyntax:Type_returnedFunction_Name(Parameter_List);/CommentdescribingwhatfunctiondoesFunctiondefinitionDescribeshowthefunctiondoesitstaskCanappearbeforeorafterthefunctioniscalledSyntax:Type_returnedFunction_Name(Parameter_List)/codetomakethefunctionwork,Slide4-18,;,Programmer-DefinedFunctions,Slide4-19,FunctionDeclaration,TellsthereturntypeTellsthenameofthefunctionTellshowmanyargumentsareneededTellsthetypesoftheargumentsTellstheformalparameternamesFormalparametersarelikeplaceholdersfortheactualargumentsusedwhenthefunctioniscalledFormalparameternamescanbeanyvalididentifierExample:doubletotal_cost(intnumber_par,doubleprice_par);/Computetotalcostincluding5%salestaxon/number_paritemsatcostofprice_pareach,Slide4-20,functionheader,functionbody,FunctionDefinition,ProvidesthesameinformationasthedeclarationDescribeshowthefunctiondoesitstaskExample:doubletotal_cost(intnumber_par,doubleprice_par)constdoubleTAX_RATE=0.05;/5%taxdoublesubtotal;subtotal=price_par*number_par;return(subtotal+subtotal*TAX_RATE);,Slide4-21,TheReturnStatement,EndsthefunctioncallReturnsthevaluecalculatedbythefunctionSyntax:returnexpression;expressionperformsthecalculationorexpressionisavariablecontainingthecalculatedvalueExample:returnsubtotal+subtotal*TAX_RATE;,TellsthenameofthefunctiontouseListstheargumentsIsusedinastatementwherethereturnedvaluemakessenseExample:doublebill=total_cost(number,price);,Slide4-22,Display4.3,TheFunctionCall,Thevaluesoftheargumentsarepluggedintotheformalparameters(Call-by-valuemechanismwithcall-by-valueparameters)Thefirstargumentisusedforthefirstformalparameter,thesecondargumentforthesecondformalparameter,andsoforth.Thevaluepluggedintotheformalparameterisusedinallinstancesoftheformalparameterinthefunctionbody,Slide4-23,Display4.4(1),Display4.4(2),FunctionCallDetails,Slide4-24,AlternateDeclarations,TwoformsforfunctiondeclarationsListformalparameternamesListtypesofformalparmeters,butnotnamesFirstaidsdescriptionofthefunctionincommentsExamples:doubletotal_cost(intnumber_par,doubleprice_par);doubletotal_cost(int,double);Functionheadersmustalwayslistformalparameternames!,Compilerchecksthatthetypesoftheargumentsarecorrectandinthecorrectsequence.CompilercannotcheckthatargumentsareinthecorrectlogicalorderExample:Giventhefunctiondeclaration:chargrade(intreceived_par,intmin_score_par);intreceived=95,min_score=60;coutgrade(min_score,received);Producesafaultyresultbecausetheargumentsarenotinthecorrectlogicalorder.Thecompilerwillnotcatchthis!,Slide4-25,Display4.5(1),OrderofArguments,Display4.5(2),WithinafunctiondefinitionVariablesmustbedeclaredbeforetheyareusedVariablesaretypicallydeclaredbeforetheexecutablestatementsbeginAtleastonereturnstatementmustendthefunctionEachbranchofanif-elsestatementmighthaveitsownreturnstatement,Slide4-26,Display4.6,FunctionDefinitionSyntax,Slide4-27,PlacingDefinitions,AfunctioncallmustbeprecededbyeitherThefunctionsdeclarationorThefunctionsdefinitionIfthefunctionsdefinitionprecedesthecall,adeclarationisnotneededPlacingthefunctiondeclarationpriortothemainfunctionandthefunctiondefinitionafterthemainfunctionleadsnaturallytobuildingyourownlibrariesinthefuture.,Slide4-28,Section4.3Conclusion,CanyouWriteafunctiondeclarationandafunctiondefinitionforafunctionthattakesthreearguments,alloftypeint,andthatreturnsthesumofitsthreearguments?Describethecall-by-valueparametermechanism?Writeafunctiondeclarationandafunctiondefinitionforafunctionthattakesoneargumentoftypeintandoneargumentoftypedouble,andthatreturnsavalueoftypedoublethatistheaverageofthetwoarguments?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,4.4,ProceduralAbstraction,Slide4-30,ProceduralAbstraction,TheBlackBoxAnalogyAblackboxreferstosomethingthatweknowhowtouse,butthemethodofoperationisunknownApersonusingaprogramdoesnotneedtoknowhowitiscodedApersonusingaprogramneedstoknowwhattheprogramdoes,nothowitdoesitFunctionsandtheBlackBoxAnalogyAprogrammerwhousesafunctionneedstoknowwhatthefunctiondoes,nothowitdoesitAprogrammerneedstoknowwhatwillbeproducediftheproperargumentsareputintothebox,Slide4-31,InformationHiding,DesigningfunctionsasblackboxesisanexampleofinformationhidingThefunctioncanbeusedwithoutknowinghowitiscodedThefunctionbodycanbe“hiddenfromview”,DesigningwiththeblackboxinmindallowsusTochangeorimproveafunctiondefinitionwithoutforcingprogrammersusingthefunctiontochangewhattheyhavedoneToknowhowtouseafunctionsimplybyreadingthefunctiondeclarationanditscomment,Slide4-32,Display4.7,FunctionImplementationsandTheBlackBox,Slide4-33,ProceduralAbstractionandC+,ProceduralAbstractioniswritingandusingfunctionsasiftheywereblackboxesProcedureisageneraltermmeaninga“functionlike”setofinstructionsAbstractionimpliesthatwhenyouuseafunctionasablackbox,youabstractawaythedetailsofthecodeinthefunctionbody,Slide4-34,ProceduralAbstractionandFunctions,WritefunctionssothedeclarationandcommentisallaprogrammerneedstousethefunctionFunctioncommentshouldtellallconditionsrequiredofargumentstothefunctionFunctioncommentshoulddescribethereturnedvalueVariablesusedinthefunction,otherthantheformalparameters,shouldbedeclaredinthefunctionbody,Functionsaredesignedasself-containedmodulesDifferentprogrammersmaywriteeachfunctionProgrammerschoosemeaningfulnamesforformalparametersFormalparameternamesmayormaynotmatchvariablenamesusedinthemainpartoftheprogramItdoesnotmatterifformalparameternamesmatchothervariablenamesintheprogramRememberthatonlythevalueoftheargumentispluggedintotheformalparameter,Slide4-35,Display4.8,FormalParameterNames,Slide4-36,CaseStudyBuyingPizza,Whatsizepizzaisthebestbuy?Whichsizegivesthelowestcostpersquareinch?PizzasizesgivenindiameterQuantityofpizzaisbasedontheareawhichisproportionaltothesquareoftheradius,Slide4-37,BuyingPizzaProblemDefinition,Input:DiameteroftwosizesofpizzaCostofthesametwosizesofpizzaOutput:CostpersquareinchforeachsizeofpizzaWhichsizeisthebestbuyBasedonlowestpricepersquareinchIfcostpersquareinchisthesame,thesmallersizewillbethebetterbuy,Slide4-38,BuyingPizzaProblemAnalysis,Subtask1GettheinputdataforeachsizeofpizzaSubtask2ComputepriceperinchforsmallerpizzaSubtask3ComputepriceperinchforlargerpizzaSubtask4DeterminewhichsizeisthebetterbuySubtask5Outputtheresults,Slide4-39,BuyingPizzaFunctionAnalysis,Subtask2andsubtask3shouldbeimplementedasasinglefunctionbecauseSubtask2andsubtask3areidenticaltasksThecalculationforsubtask3isthesameasthecalculationforsubtask2withdifferentargumentsSubtask2andsubtask3eachreturnasinglevalueChooseanappropriatenameforthefunctionWelluseunitprice,Slide4-40,BuyingPizzaunitpriceDeclaration,doubleunitprice(intdiameter,intdoubleprice);/Returnsthepricepersquareinchofapizza/Theformalparameternameddiameteristhe/diameterofthepizzaininches.Theformal/parameternamedpriceisthepriceofthe/pizza.,Slide4-41,BuyingPizzaAlgorithmDesign,Subtask1Askfortheinputvaluesandstoretheminvariablesdiameter_smalldiameter_largeprice_smallprice_largeSubtask4ComparecostpersquareinchofthetwopizzasusingthelessthanoperatorSubtask5Standardoutputoftheresults,Slide4-42,BuyingPizzaunitpriceAlgorithm,Subtasks2and3areimplementedascallstofunctionunitpriceunitpricealgorithmComputetheradiusofthepizzaComputertheareaofthepizzausingReturnthevalueof(price/area),Slide4-43,BuyingPizzaunitpricePseudocode,PseudocodeMixtureofC+andenglishAllowsustomakethealgorithmmoreprecisewithoutworryingaboutthedetailsofC+syntaxunitpricepseudocoderadius=onehalfofdiameter;area=*radius*radiusreturn(price/area),Slide4-44,BuyingPizzaTheCallsofunitprice,Mainpartoftheprogramimplementscallsofunitpriceasdoubleunit_price_small,unit_price_large;unit_price_small=unitprice(diameter_small,price_small);unit_price_large=unitprice(diameter_large,price_large);,Slide4-45,BuyingPizzaFirsttryatunitprice,doubleunitprice(intdiameter,doubleprice)constdoublePI=3.14159;doubleradius,area;radius=diameter/2;area=PI*radius*radius;return(price/area);Oops!Radiusshouldincludethefractionalpart,doubleunitprice(intdiameter,doubleprice)constdoublePI=3.14159;doubleradius,area;radius=diameter/static_cast(2);area=PI*radius*radius;return(price/area);Nowradiuswillincludefractionalpartsradius=diameter/2.0;/Thiswouldalsowork,Slide4-46,Display4.10(1),Display4.10(2),BuyingPizzaSecondtryatunitprice,Slide4-47,ProgramTesting,ProgramsthatcompileandruncanstillproduceerrorsTestingincreasesconfidencethattheprogramworkscorrectlyRuntheprogramwithdatathathasknownoutputYoumayhavedeterminedthisoutputwithpencilandpaperoracalculatorRuntheprogramonseveraldifferentsetsofdataYourfirstsetofdatamayproducecorrectresultsinspiteofalogicalerrorinthecodeRemembertheintegerdivisionproblem?Ifthereisnofractionalremainder,integerdivisionwillgiveapparentlycorrectresults,Slide4-48,UsePseudocode,PseudocodeisamixtureofEnglishandtheprogramminglanguageinusePseudocodesimplifiesalgorithmdesignbyallowingyoutoignorethespecificsyntaxoftheprogramminglanguageasyouworkoutthedetailsofthealgorithmIfthestepisobvious,useC+IfthestepisdifficulttoexpressinC+,useEnglish,Slide4-49,Section4.4Conclusion,CanyouDescribethepurposeofthecommentthataccompaniesafunctiondeclaration?Describewhatitmeanstosayaprogrammershouldbeabletotreatafunctionasablackbox?Describewhatitmeansfortwofunctionstobeblackboxequivalent?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,4.5,LocalVariables,Variablesdeclaredinafunction:Arelocaltothatfunction,theycannotbeusedfromoutsidethefunctionHavethefunctionastheirscopeVariablesdeclaredinthemainpartofaprogram:Arelocaltothemainpartoftheprogram,theycannotbeusedfromoutsidethemainpartHavethemainpartastheirscope,Slide4-51,Display4.11(1),Display4.11(2),LocalVariables,GlobalNamedConstantAvailabletomorethanonefunctionaswellasthemainpartoftheprogramDeclaredoutsideanyfunctionbodyDeclaredoutsidethemainfunctionbodyDeclaredbeforeanyfunctionthatusesitExample:constdoublePI=3.14159;doublevolume(double);intmain()PIisavailabletothemainfunctionandtofunctionvolume,Slide4-52,Display4.12(1),Display4.12(2),GlobalConstants,Slide4-53,GlobalVariables,GlobalVariable-rarelyusedwhenmorethanonefunctionmustuseacommonvariableDeclaredjustlikeaglobalconstantexceptconstisnotusedGenerallymakeprogramsmoredifficulttounderstandandmaintain,FormalParametersareactuallyvariablesthatarelocaltothefunctiondefinitionTheyareusedjustasiftheyweredeclaredinthefunctionbodyDoNOTre-declaretheformalparametersinthefunctionbody,theyaredeclaredinthefunctiondeclarationThecall-by-valuemechanismWhenafunctioniscalledtheformalparametersareinitializedtothevaluesoftheargumentsinthefunctioncall,Slide4-54,Display4.13(1),Display4.13(2),FormalParametersareLocalVariables,Thestartofafileisnotalwaysthebestplaceforusingnamespacestd;DifferentfunctionsmayusedifferentnamespacesPlacingusingnamespacestd;insidethestartingbraceofafunctionAllowstheuseofdifferentnamespacesindifferentfunctionsMakesthe“using”directivelocaltothefunction,Slide4-55,Display4.14(1),Display4.14(2),NamespacesRevisited,n!Representsthefactorialfunctionn!=1x2x3xxnTheC+versionofthefactorialfunctionfoundinDisplay3.14Requiresoneargumentoftypeint,nReturnsavalueoftypeintUsesalocalvariabletostorethecurrentproductDecrementsneachtimeitdoesanothermultiplicationn*n-1*n-2*1,Slide4-56,Display4.15,Example:Factorial,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,4.6,OverloadingFunctionNames,Slide4-58,OverloadingFunctionNames,C+allowsmorethanonedefinitionforthesamefunctionnameVeryconvenientforsituationsinwhichthe“same”functionisneededfordifferentnumbersortypesofargumentsOverloadingafunctionnamemeansprovidingmorethanonedeclarationanddefinitionusingthesamefunctionname,Slide4-59,OverloadingExamples,doubleave(doublen1,doublen2)return(n1+n2)/2);doubleave(doublen1,doublen2,doublen3)return(n1+n2+n3)/3);Compilerchecksthenumberandtypesofargumentsinthefunctioncalltodecidewhichfunctiontousecoutave(10,20,30);usestheseconddefinition,OverloadedfunctionsMusthavedifferentnumbersofformalparametersAND/ORMusthaveatleastonedifferenttypeofparameterMustreturnavalueofthesametype,Slide4-60,Display4.16,OverloadingDetails,RevisingthePizzaBuyingprogramRectangularpizzasarenowoffered!ChangetheinputandaddafunctiontocomputetheunitpriceofarectangularpizzaThenewfunctioncouldbenamedunitprice_rectangularOr,thenewfunctioncouldbeanew(overloaded)versionoftheunitpricefunctionthatisalreadyusedExample:doubleunitprice(intlength,intwidth,doubleprice)doublearea=length*width;return(price/area);,Slide4-61,Display4.17(13),OverloadingExample,Slide4-62,AutomaticTypeConversion,Giventhedefinitiondoublempg(doublemiles,doublegallons)return(miles/gallons);whatwillhappenifmpgiscalledinthisway?coutmpg(45,2)“milespergallon”;Theval
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 酒店托管活动策划方案
- 外企员工创新管理制度
- 2025福建漳州市长泰区医院招聘编外收费人员1人考试笔试模拟试题及答案解析
- 2025贵州省农业科学院附属中学比选4名高中教师实施考试笔试模拟试题及答案解析
- 医院扫黑除恶年度总结(3篇)
- 2025年单招信息技术操作卷历年真题精讲与练习
- 2025贵州安顺市第一高级中学参加贵州省省校合作赴省外知名高校引才后续招聘考试笔试备考试题及答案解析
- 2025重庆涪陵区南沱镇人民政府选聘4人考试笔试参考题库附答案解析
- 2025年永丰县自然资源局面向社会公开招聘编外工作人员考试笔试参考题库附答案解析
- 2026中国电科产业基础研究院校园招聘开启笔试考试参考试题及答案解析
- 肝癌介入加靶向治疗讲课件
- 毕业设计(论文)-空气压缩机结构设计
- 2024DBJ33T1095-预拌砂浆应用技术规程
- JG/T 160-2004混凝土用膨胀型、扩孔型建筑锚栓
- 高一家长会化学教师课件
- 2025年中国电脑CPU散热器市场调查研究报告
- 2025年保密观考试题库及答案(真题版)
- 超市店长职责与工作流程
- 重症监护室护理管理制度范本
- 《社会体育指导员技术等级培训教材》
- 科研项目经费预算表格-科研项目经费明细
评论
0/150
提交评论