已阅读5页,还剩60页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Copyright2008PearsonAddison-Wesley.Allrightsreserved.,Chapter5,FunctionsforAllSubtasks,Slide5-3,Overview,5.1voidFunctions5.2Call-By-ReferenceParameters5.3UsingProceduralAbstraction5.4TestingandDebugging,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,5.1,voidFunctions,Slide5-5,void-Functions,Intop-downdesign,asubtaskmightproduceNovalue(justinputoroutputforexample)OnevalueMorethanonevalueWehaveseenhowtoimplementfunctionsthatreturnonevalueAvoid-functionimplementsasubtaskthatreturnsnovalueormorethanonevalue,Twomaindifferencesbetweenvoid-functiondefinitionsandthedefinitionsoffunctionsthatreturnonevalueKeywordvoidreplacesthetypeofthevaluereturnedvoidmeansthatnovalueisreturnedbythefunctionThereturnstatementdoesnotincludeandexpressionExample:voidshow_results(doublef_degrees,doublec_degrees)usingnamespacestd;coutf_degrees“degreesFahrenheitiseuivalentto“endlc_degrees“degreesCelsius.”endl;return;,Slide5-6,Display5.1,void-FunctionDefinition,Slide5-7,Usingavoid-Function,void-functioncallsareexecutablestatementsTheydonotneedtobepartofanotherstatementTheyendwithasemi-colonExample:show_results(32.5,0.3);NOT:coutshow_results(32.5,0.3);,Slide5-8,void-FunctionCalls,MechanismisnearlythesameasthefunctioncallswehaveseenArgumentvaluesaresubstitutedfortheformalparametersItisfairlycommontohavenoparametersinvoid-functionsInthiscasetherewillbenoargumentsinthefunctioncallStatementsinfunctionbodyareexecutedOptionalreturnstatementendsthefunctionReturnstatementdoesnotincludeavaluetoreturnReturnstatementisimplicitifitisnotincluded,ThefunctionsjustdevelopedcanbeusedinaprogramtoconvertFahrenheittemperaturestoCelciususingtheformulaC=(5/9)(F32)Doyouseetheintegerdivisionproblem?,Slide5-9,Display5.2(1),Display5.2(2),Example:ConvertingTemperatures,Isareturn-statementeverneededinavoid-functionsincenovalueisreturned?Yes!Whatifabranchofanif-elsestatementrequiresthatthefunctionendstoavoidproducingmoreoutput,orcreatingamathematicalerror?void-functioninDisplay5.3,avoidsdivisionbyzerowithareturnstatement,Slide5-10,Display5.3,void-FunctionsWhyUseaReturn?,Slide5-11,TheMainFunction,Themainfunctioninaprogramisusedlikeavoidfunctiondoyouhavetoendtheprogramwithareturn-statement?Becausethemainfunctionisdefinedtoreturnavalueoftypeint,thereturnisneededC+standardsaysthereturn0canbeomitted,butmanycompilersstillrequireit,Slide5-12,Section5.1Conclusion,CanyouDescribethedifferencesbetweenvoid-functionsandfunctionsthatreturnonevalue?Tellwhathappensifyouforgetthereturn-statementinavoid-function?Distinguishbetweenfunctionsthatareusedasexpressionsandthoseusedasstatements?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,5.2,Call-By-ReferenceParameters,Slide5-14,Call-by-ReferenceParameters,Call-by-valueisnotadequatewhenweneedasub-tasktoobtaininputvaluesCall-by-valuemeansthattheformalparametersreceivethevaluesoftheargumentsToobtaininputvalues,weneedtochangethevariablesthatareargumentstothefunctionRecallthatwehavechangedthevaluesofformalparametersinafunctionbody,butwehavenotchangedtheargumentsfoundinthefunctioncallCall-by-referenceparametersallowustochangethevariableusedinthefunctioncallArgumentsforcall-by-referenceparametersmustbevariables,notnumbers,voidget_input(doublevoidf(int,Call-by-valueThefunctioncall:f(age);voidf(intvar_par);,CallComparisonsCallByReferencevsValue,Memory,Slide5-18,Example:swap_values,voidswap(intfirst_numissubstitutedforvariable1intheparameterlistsecond_numissubstitutedforvariable2intheparameterlisttempisassignedthevalueofvariable1(first_num)sincethenextlinewillloosethevalueinfirst_numvariable1(first_num)isassignedthevalueinvariable2(second_num)variable2(second_num)isassignedtheoriginalvalueofvariable1(first_num)whichwasstoredintemp,Slide5-19,MixedParameterLists,Call-by-valueandcall-by-referenceparameterscanbemixedinthesamefunctionExample:voidgood_stuff(intpar1andpar3arecall-by-referenceformalparametersChangesinpar1andpar3changetheargumentvariablepar2isacall-by-valueformalparameterChangesinpar2donotchangetheargumentvariable,Howdoyoudecidewhetheracall-by-referenceorcall-by-valueformalparameterisneeded?Doesthefunctionneedtochangethevalueofthevariableusedasanargument?Yes?Useacall-by-referenceformalparameterNo?Useacall-by-valueformalparameter,Slide5-20,Display5.6,ChoosingParameterTypes,Ifafunctionistochangethevalueofavariablethecorrespondingformalparametermustbeacall-by-referenceparameterwithanampersand(/Precondition:fahrenheitisatemperature/expressedindegreesFahrenheit/Postcondition:Returnstheequivalenttemperature/expressedindegreesCelsius,Slide5-29,Whyusepreconditionsandpostconditions?,PreconditionsandpostconditionsshouldbethefirststepindesigningafunctionspecifywhatafunctionshoulddoAlwaysspecifywhatafunctionshoulddobeforedesigninghowthefunctionwilldoitMinimizedesignerrorsMinimizetimewastedwritingcodethatdoesntmatchthetaskathand,Slide5-30,CaseStudySupermarketPricing,ProblemdefinitionDetermineretailpriceofanitemgivensuitableinput5%markupifitemshouldsellinaweek10%markupifitemexpectedtotakemorethanaweek5%forupto7days,changesto10%at8daysInputThewholesalepriceandtheestimateofdaysuntilitemsellsOutputTheretailpriceoftheitem,Slide5-31,SupermarketPricing:ProblemAnalysis,ThreemainsubtasksInputthedataComputetheretailpriceoftheitemOutputtheresultsEachtaskcanbeimplementedwithafunctionNoticetheuseofcall-by-valueandcall-by-referenceparametersinthefollowingfunctiondeclarations,Slide5-32,SupermarketPricing:Functionget_input,voidget_input(double/Precondition:Userisreadytoentervalues/correctly./Postcondition:Thevalueofcosthasbeensetto/thewholesalecostofoneitem./Thevalueofturnoverhasbeen/settotheexpectednumberof/daysuntiltheitemissold.,Slide5-33,SupermarketPricing:Functionprice,doubleprice(doublecost,intturnover);/Precondition:costisthewholesalecostofone/item.turnoveristheexpected/numberofdaysuntiltheitemis/sold./Postcondition:returnstheretailpriceoftheitem,Slide5-34,SupermarketPricing:Functiongive_output,voidgive_output(doublecost,intturnover,doubleprice);/Precondition:costisthewholesalecostofoneitem;/turnoveristheexpectedtimeuntilsale/oftheitem;priceistheretailpriceof/theitem./Postcondition:Thevaluesofcost,turnover,andprice/beenwrittentothescreen.,Slide5-35,SupermarketPricing:Themainfunction,Withthefunctionsdeclared,wecanwritethemainfunction:intmain()doublewholesale_cost,retail_price;intshelf_time;get_input(wholesale_cost,shelf_time);retail_price=price(wholesale_cost,shelf_time);give_output(wholesale_cost,shelf_time,retail_price);return0;,Slide5-36,SupermarketPricing:AlgorithmDesign-price,Implementationsofget_inputandgive_outputarestraightforward,soweconcentrateonthepricefunctionpseudocodeforthepricefunctionIfturnover=7daysthenreturn(cost+5%ofcost);elsereturn(cost+10%ofcost);,Slide5-37,SupermarketPricing:ConstantsforThepriceFunction,ThenumericvaluesinthepseudocodewillberepresentedbyconstantsConstdoubleLOW_MARKUP=0.05;/5%ConstdoubleHIGH_MARKUP=0.10;/10%ConstintTHRESHOLD=7;/At8daysuse/HIGH_MARKUP,Thebodyofthepricefunctionif(turnover=THRESHOLD)return(cost+(LOW_MARKUP*cost);elsereturn(cost+(HIGH_MARKUP*cost);Seethecompleteprogramin,Slide5-38,Display5.9(1),Display5.9(2),Display5.9(3),SupermarketPricing:CodingThepriceFunction,Slide5-39,SupermarketPricing:ProgramTesting,TestingstrategiesUsedatathattestsboththehighandlowmarkupcasesTestboundaryconditions,wheretheprogramisexpectedtochangebehaviorormakeachoiceInfunctionprice,7daysisaboundaryconditionTestforexactly7daysaswellasonedaymoreandonedayless,Slide5-40,Section5.3Conclusion,CanyouDefineafunctioninthebodyofanotherfunction?Callonefunctionfromthebodyofanotherfunction?Givepreconditionsandpostconditionsforthepredefinedfunctionsqrt?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,5.4,TestingandDebugging,EachfunctionshouldbetestedasaseparateunitTestingindividualfunctionsfacilitatesfindingmistakesDriverprogramsallowtestingofindividualfunctionsOnceafunctionistested,itcanbeusedinthedriverprogramtotestotherfunctionsFunctionget_inputistestedinthedriverprogramofand,Slide5-42,Display5.10(1),Display5.10(2),TestingandDebuggingFunctions,Whenafunctionbeingtestedcallsotherfunctionsthatarenotyettested,useastubAstubisasimplifiedversionofafunctionStubsareusuallyprovidevaluesfortestingratherthanperformtheintendedcalculationStubsshouldbesosimplethatyouhaveconfidencetheywillperformcorrectlyFunctionpriceisusedasastubtotesttherestofthesupermarketpricingprograminand,Slide5-43,Display5.11(1),Display5.11(2),Stubs,Slide5-44,RuleforTestingFunctions,FundamentalRuleforTestingFunctionsTesteveryfunctioninaprograminw
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 物业合作协议合同范本
- 直播平台服务合同协议
- 监控安装工程合同范本
- 租售轻卡货车合同范本
- 监控平台租用合同范本
- 礼盒水果采购合同范本
- 项目承包协议劳务合同
- 美食街公司免责协议书
- 邮局皮带采购合同范本
- 设备合同中的技术协议
- 2025广东深圳市龙华区招聘社区网格员72人考试笔试参考题库附答案解析
- 服装店店长岗位职责详述
- 工业废水处理工岗位标准化技术规程
- 【MOOC】《创业团队建设与管理》(首都经济贸易大学)章节期末慕课答案
- 医学遗传学(第3版)课件 7-8系谱上课
- 新概念二Lesson7TooLate知识点总
- 护理员安全生产责任制
- GA 576-2018防尾随联动互锁安全门通用技术条件
- 部编版语文一年级上册第二单元大单元作业设计
- 计票结果报告单工会
- 食品留样表 (2)
评论
0/150
提交评论