




已阅读5页,还剩94页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter4,ProceduralAbstractionandFunctionsThatReturnaValue,Overview,4.1Top-DownDesign4.2PredefinedFunctions4.3Programmer-DefinedFunctions4.4ProceduralAbstraction4.5LocalVariables4.6OverloadingFunctionNames,Slide4-3,4.1,Top-DownDesign,TopDownDesign,TowriteaprogramDevelopthealgorithmthattheprogramwilluseTranslatethealgorithmintotheprogramminglanguageTopDownDesign(alsocalledstepwiserefinement)BreakthealgorithmintosubtasksBreakeachsubtaskintosmallersubtasksEventuallythesmallersubtasksaretrivialtoimplementintheprogramminglanguage,Slide4-5,BenefitsofTopDownDesign,Subtasks,orfunctionsinC+,makeprogramsEasiertounderstandEasiertochangeEasiertowriteEasiertotestEasiertodebugEasierforteamstodevelop,Slide4-6,4.2,PredefinedFunctions,PredefinedFunctions,C+comeswithlibrariesofpredefinedfunctionsExample:sqrtfunctionthe_root=sqrt(9.0);returns,orcomputes,thesquarerootofanumberThenumber,9,iscalledtheargumentthe_rootwillcontain3.0,Slide4-8,FunctionCalls,sqrt(9.0)isafunctioncallItinvokes,orsetsinaction,thesqrtfunctionTheargument(9),canalsobeavariableoranexpressionAfunctioncallcanbeusedlikeanyexpressionbonus=sqrt(sales)/10;Cout“Thesideofasquarewitharea“area“is“sqrt(area);,Slide4-9,Display4.1,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-10,FunctionLibraries,PredefinedfunctionsarefoundinlibrariesThelibrarymustbe“included”inaprogramtomakethefunctionsavailableAnincludedirectivetellsthecompilerwhichlibraryheaderfiletoinclude.Toincludethemathlibrarycontainingsqrt():#includeNewerstandardlibraries,suchascmath,alsorequirethedirectiveusingnamespacestd;,Slide4-11,OtherPredefinedFunctions,abs(x)-intvalue=abs(-8);ReturnsabsolutevalueofargumentxReturnvalueisoftypeintArgumentisoftypexFoundinthelibrarycstdlibfabs(x)-doublevalue=fabs(-8.0);ReturnstheabsolutevalueofargumentxReturnvalueisoftypedoubleArgumentisoftypedoubleFoundinthelibrarycmath,Slide4-12,Display4.2,RandomNumberGeneration,Reallypseudo-randomnumbers1.Seedtherandomnumbergeneratoronlyonce#include#includesrand(time(0);2.Therand()functionreturnsarandomintegerthatisgreaterthanorequalto0andlessthanRAND_MAXrand();,Slide1-13,RandomNumbers,Use%and+toscaletothenumberrangeyouwantForexampletogetarandomnumberfrom1-6tosimulaterollingasix-sideddie:intdie=(rand()%6)+1;Canyousimulaterollingtwodice?Generatingarandomnumberxwhere10x21?,Slide1-14,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-15,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-16,Integerdivisionoccursbeforetypecast,OldStyleTypeCast,C+isanevolvinglanguageThisoldermethodoftypecastingmaybediscontinuedinfutureversionsofC+candy_per_person=double(total_candy)/number_of_people;,Slide4-17,Section4.2Conclusion,Slide4-18,CanyouDeterminethevalueofd?doubled=11/2;Determinethevalueofpow(2,3)fabs(-3.5)sqrt(pow(3,2)7/abs(-2)ceil(5.8)floor(5.8)ConvertthefollowingtoC+,4.3,Programmer-DefinedFunctions,Programmer-DefinedFunctions,TwocomponentsofafunctiondefinitionFunctiondeclaration(orfunctionprototype)ShowshowthefunctioniscalledMustappearinthecodebeforethefunctioncanbecalledSyntax:Type_returnedFunction_Name(Parameter_List);/CommentdescribingwhatfunctiondoesFunctiondefinitionDescribeshowthefunctiondoesitstaskCanappearbeforeorafterthefunctioniscalledSyntax:Type_returnedFunction_Name(Parameter_List)/codetomakethefunctionwork,Slide4-20,;,FunctionDeclaration,TellsthereturntypeTellsthenameofthefunctionTellshowmanyargumentsareneededTellsthetypesoftheargumentsTellstheformalparameternamesFormalparametersarelikeplaceholdersfortheactualargumentsusedwhenthefunctioniscalledFormalparameternamescanbeanyvalididentifierExample:doubletotal_cost(intnumber_par,doubleprice_par);/Computetotalcostincluding5%salestaxon/number_paritemsatcostofprice_pareach,Slide4-21,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-22,functionheader,functionbody,TheReturnStatement,EndsthefunctioncallReturnsthevaluecalculatedbythefunctionSyntax:returnexpression;expressionperformsthecalculationorexpressionisavariablecontainingthecalculatedvalueExample:returnsubtotal+subtotal*TAX_RATE;,Slide4-23,TheFunctionCall,TellsthenameofthefunctiontouseListstheargumentsIsusedinastatementwherethereturnedvaluemakessenseExample:doublebill=total_cost(number,price);,Slide4-24,Display4.3,FunctionCallDetails,Thevaluesoftheargumentsarepluggedintotheformalparameters(Call-by-valuemechanismwithcall-by-valueparameters)Thefirstargumentisusedforthefirstformalparameter,thesecondargumentforthesecondformalparameter,andsoforth.Thevaluepluggedintotheformalparameterisusedinallinstancesoftheformalparameterinthefunctionbody,Slide4-25,Display4.4,AlternateDeclarations,TwoformsforfunctiondeclarationsListformalparameternamesListtypesofformalparmeters,butnotnamesFirstaidsdescriptionofthefunctionincommentsExamples:doubletotal_cost(intnumber_par,doubleprice_par);doubletotal_cost(int,double);Functionheadersmustalwayslistformalparameternames!,Slide4-26,OrderofArguments,Compilerchecksthatthetypesoftheargumentsarecorrectandinthecorrectsequence.CompilercannotcheckthatargumentsareinthecorrectlogicalorderExample:Giventhefunctiondeclaration:chargrade(intreceived_par,intmin_score_par);intreceived=95,min_score=60;cout=10)/Returnsthepricepersquareinchofapizza/Theformalparameternameddiameteristhe/diameterofthepizzaininches.Theformal/parameternamedpriceisthepriceofthe/pizza.,Slide4-44,BuyingPizzaAlgorithmDesign,Subtask1Askfortheinputvaluesandstoretheminvariablesdiameter_smalldiameter_largeprice_smallprice_largeSubtask4ComparecostpersquareinchofthetwopizzasusingthelessthanoperatorSubtask5Standardoutputoftheresults,Slide4-45,BuyingPizzaunitpriceAlgorithm,Slide4-46,Subtasks2and3areimplementedascallstofunctionunitpriceunitpricealgorithmComputetheradiusofthepizzaComputertheareaofthepizzausingReturnthevalueof(price/area),BuyingPizzaunitpricePseudocode,PseudocodeMixtureofC+andenglishAllowsustomakethealgorithmmoreprecisewithoutworryingaboutthedetailsofC+syntaxunitpricepseudocoderadius=onehalfofdiameter;area=*radius*radiusreturn(price/area),Slide4-47,BuyingPizzaTheCallsofunitprice,Mainpartoftheprogramimplementscallsofunitpriceasdoubleunit_price_small,unit_price_large;unit_price_small=unitprice(diameter_small,price_small);unit_price_large=unitprice(diameter_large,price_large);,Slide4-48,BuyingPizzaFirsttryatunitprice,doubleunitprice(intdiameter,doubleprice)constdoublePI=3.14159;doubleradius,area;radius=diameter/2;area=PI*radius*radius;return(price/area);Oops!Radiusshouldincludethefractionalpart,Slide4-49,BuyingPizzaSecondtryatunitprice,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-50,Display4.10(1),Display4.10(2),ProgramTesting,ProgramsthatcompileandruncanstillproduceerrorsTestingincreasesconfidencethattheprogramworkscorrectlyRuntheprogramwithdatathathasknownoutputYoumayhavedeterminedthisoutputwithpencilandpaperoracalculatorRuntheprogramonseveraldifferentsetsofdataYourfirstsetofdatamayproducecorrectresultsinspiteofalogicalerrorinthecodeRemembertheintegerdivisionproblem?Ifthereisnofractionalremainder,integerdivisionwillgiveapparentlycorrectresults,Slide4-51,UsePseudocode,PseudocodeisamixtureofEnglishandtheprogramminglanguageinusePseudocodesimplifiesalgorithmdesignbyallowingyoutoignorethespecificsyntaxoftheprogramminglanguageasyouworkoutthedetailsofthealgorithmIfthestepisobvious,useC+IfthestepisdifficulttoexpressinC+,useEnglish,Slide4-52,Section4.4Conclusion,CanyouDescribethepurposeofthecommentthataccompaniesafunctiondeclaration?Describewhatitmeanstosayaprogrammershouldbeabletotreatafunctionasablackbox?Describewhatitmeansfortwofunctionstobeblackboxequivalent?,Slide4-53,4.5,LocalVariables,LocalVariables,Variablesdeclaredinafunction:Arelocaltothatfunction,theycannotbeusedfromoutsidethefunctionHavethefunctionastheirscopeVariablesdeclaredinthemainpartofaprogram:Arelocaltothemainpartoftheprogram,theycannotbeusedfromoutsidethemainpartHavethemainpartastheirscope,Slide4-55,Display4.11(1),Display4.11(2),GlobalConstants,GlobalNamedConstantAvailabletomorethanonefunctionaswellasthemainpartoftheprogramDeclaredoutsideanyfunctionbodyDeclaredoutsidethemainfunctionbodyDeclaredbeforeanyfunctionthatusesitExample:constdoublePI=3.14159;doublevolume(double);intmain()PIisavailabletothemainfunctionandtofunctionvolume,Slide4-56,Display4.12(1),Display4.12(2),GlobalVariables,GlobalVariable-rarelyusedwhenmorethanonefunctionmustuseacommonvariableDeclaredjustlikeaglobalconstantexceptconstisnotusedGenerallymakeprogramsmoredifficulttounderstandandmaintain,Slide4-57,FormalParametersareLocalVariables,FormalParametersareactuallyvariablesthatarelocaltothefunctiondefinitionTheyareusedjustasiftheyweredeclaredinthefunctionbodyDoNOTre-declaretheformalparametersinthefunctionbody,theyaredeclaredinthefunctiondeclarationThecall-by-valuemechanismWhenafunctioniscalledtheformalparametersareinitializedtothevaluesoftheargumentsinthefunctioncall,Slide4-58,Display4.13(1),Display4.13(2),BlockScope,LocalandglobalvariablesconformtotherulesofBlockScopeThecodeblock(generallydefinedbythe)whereanidentifierlikeavariableisdeclareddeterminesthescopeoftheidentifierBlockscanbenested,Slide1-59,Display4.14,NamespacesRevisited,Thestartofafileisnotalwaysthebestplaceforusingnamespacestd;DifferentfunctionsmayusedifferentnamespacesPlacingusingnamespacestd;insidethestartingbraceofafunctionAllowstheuseofdifferentnamespacesindifferentfunctionsMakesthe“using”directivelocaltothefunction,Slide4-60,Display4.15(1),Display4.15(2),Example:Factorial,n!Representsthefactorialfunctionn!=1x2x3xxnTheC+versionofthefactorialfunctionfoundinDisplay3.14Requiresoneargumentoftypeint,nReturnsavalueoftypeintUsesalocalvariabletostorethecurrentproductDecrementsneachtimeitdoesanothermultiplicationn*n-1*n-2*1,Slide4-61,Display4.16,4.6,OverloadingFunctionNames,OverloadingFunctionNames,C+allowsmorethanonedefinitionforthesamefunctionnameVeryconvenientforsituationsinwhichthe“same”functionisneededfordifferentnumbersortypesofargumentsOverloadingafunctionnamemeansprovidingmorethanonedeclarationanddefinitionusingthesamefunctionname,Slide4-63,OverloadingExamples,doubleave(doublen1,doublen2)return(n1+n2)/2);doubleave(doublen1,doublen2,doublen3)return(n1+n2+n3)/3);Compilerchecksthenumberandtypesofargumentsinthefunctioncalltodecidewhichfunctiontousecoutave(10,20,30);usestheseconddefinition,Slide4-64,OverloadingDetails,OverloadedfunctionsMusthavedifferentnumbersofformalparametersAND/ORMusthaveatleastonedifferenttypeofparameterMustreturnavalueofthesametype,Slide4-65,Display4.17,OverloadingExample,RevisingthePizzaBuyingprogramRectangularpizzasarenowoffered!ChangetheinputandaddafunctiontocomputetheunitpriceofarectangularpizzaThenewfunctioncouldbenamedunitprice_rectangularOr,thenewfunctioncouldbeanew(overloaded)versionoftheunitpricefunctionthatisalreadyusedExample:doubleunitprice(intlength,intwidth,doubleprice)doublearea=length*width;return(price/area);,Slide4-66,Display4.18(13),AutomaticTypeConversion,Giventhedefinitiondoublempg(doublemiles,doublegallons)return(miles/gallons);whatwillhappenifmpgiscalledinthisway?coutmpg(45,2)“milespergallon”;Thevaluesoftheargumentswillautomaticallybeconvertedtotypedouble(45.0and2.0),Slide4-67,TypeConversionProblem,Giventhepreviousmpgdefinitionandthefollowingdefinitioninthesameprogramintmpg(intgoals,intmisses)/returnstheMeasureofPerfectGoalsreturn(goalsmisses);whathappensifmpgiscalledthiswaynow?coutmpg(45,2)“milespergallon”;ThecompilerchoosesthefunctionthatmatchesparametertypessotheMeasureofPerfe
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年河北保定曲阳县公开选聘职教中心教师18名模拟试卷附答案详解(典型题)
- 2025内蒙古气象部门招聘70人考前自测高频考点模拟试题及答案详解(典优)
- 2025广东韶关市翁源县畜牧兽医水产局补招录特聘动物防疫专员1人考前自测高频考点模拟试题及答案详解参考
- 2025年宜昌市点军区公开招聘6名社区专职工作人员(网格员)模拟试卷有完整答案详解
- 吉林省长春市2024-2025学年高三下学期质量监测(二)地理试题(解析版)
- 2025广东佛冈县水头镇选拔储备村(社区)“两委”后备人员考前自测高频考点模拟试题及一套完整答案详解
- 湖南省名校联盟2024-2025学年高一上学期入学联考地理地理试题(解析版)
- 企业财务流程合规操作保证承诺书3篇
- 2025年金华东阳市人民医院招聘编外人员8人考前自测高频考点模拟试题参考答案详解
- 租船经纪人课件
- 2025年财富管理市场客户需求与服务升级下的行业品牌建设报告
- 保险新员工考试题及答案
- 网格人员安全培训内容课件
- 2025至2030中国智能无人船行业市场发展分析及竞争态势与产业运行态势及投资规划深度研究报告
- 可靠的出租吊篮施工方案
- (2025年标准)分包意向协议书
- 2025食品经营考试题及答案
- 炼钢厂工艺技术规程
- 标本运送基础知识培训课件
- 针灸技术操作规范
- 外来施工人员安全教育培训考试试卷
评论
0/150
提交评论