![第10版教辅含答案testbank实验手册等_第1页](http://file4.renrendoc.com/view/354a4bd88f94a9aa1d06fb5e53270123/354a4bd88f94a9aa1d06fb5e532701231.gif)
![第10版教辅含答案testbank实验手册等_第2页](http://file4.renrendoc.com/view/354a4bd88f94a9aa1d06fb5e53270123/354a4bd88f94a9aa1d06fb5e532701232.gif)
![第10版教辅含答案testbank实验手册等_第3页](http://file4.renrendoc.com/view/354a4bd88f94a9aa1d06fb5e53270123/354a4bd88f94a9aa1d06fb5e532701233.gif)
![第10版教辅含答案testbank实验手册等_第4页](http://file4.renrendoc.com/view/354a4bd88f94a9aa1d06fb5e53270123/354a4bd88f94a9aa1d06fb5e532701234.gif)
![第10版教辅含答案testbank实验手册等_第5页](http://file4.renrendoc.com/view/354a4bd88f94a9aa1d06fb5e53270123/354a4bd88f94a9aa1d06fb5e532701235.gif)
下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Chapter 5Functions for All SubtasksOverview5.1 void Functions 5.2 Call-By-Reference Parameters5.3 Using Procedural Abstraction5.4 Testing and Debugging5.5 General Debugging TechniquesSlide 5- 35.1void Functionsvoid-FunctionsIn top-down design, a subtask might produceNo value (just input or output fo
2、r example)One value More than one valueWe have seen how to implement functions thatreturn one valueA void-function implements a subtask that returns no value or more than one valueSlide 5- 5void-Function DefinitionTwo main differences between void-function definitions and the definitions of function
3、s that return one valueKeyword void replaces the type of the value returnedvoid means that no value is returned by the functionThe return statement does not include and expressionExample:void showResults(double f_degrees, double c_degrees) using namespace std; cout f_degrees “ degrees Fahrenheit is
4、euivalent to “ endl c_degrees “ degrees Celsius.” endl; return;Slide 5- 6Display 5.1Using a void-Functionvoid-function calls are executable statementsThey do not need to be part of another statementThey end with a semi-colonExample: showResults(32.5, 0.3); NOT: cout showResults(32.5, 0.3);Slide 5- 7
5、void-Function CallsMechanism is nearly the same as the function calls we have seenArgument values are substituted for the formal parameters It is fairly common to have no parameters in void-functionsIn this case there will be no arguments in the function callStatements in function body are executedO
6、ptional return statement ends the functionReturn statement does not include a value to returnReturn statement is implicit if it is not includedSlide 5- 8Example: Converting TemperaturesThe functions just developed can be used in a program to convert Fahrenheit temperatures toCelcius using the formul
7、a C = (5/9) (F 32)Do you see the integer division problem?Slide 5- 9Display 5.2 (1)Display 5.2 (2)void-FunctionsWhy Use a Return?Is a return-statement ever needed in avoid-function since no value is returned?Yes!What if a branch of an if-else statement requires that the function ends to avoid produc
8、ing more output, or creating a mathematical error?void-function in Display 5.3, avoids division by zerowith a return statementSlide 5- 10Display 5.3The Main FunctionThe main function in a program is used like avoid functiondo you have to end the programwith a return-statement?Because the main functi
9、on is defined to return a value of type int, the return is neededC+ standard says the return 0 can be omitted, but many compilers still require itSlide 5- 11Section 5.1 ConclusionCan youDescribe the differences between void-functions and functions that return one value?Tell what happens if you forge
10、t the return-statementin a void-function?Distinguish between functions that are used as expressions and those used as statements?Slide 5- 125.2Call-By-Reference ParametersCall-by-Reference ParametersCall-by-value is not adequate when we need a sub-task to obtain input valuesCall-by-value means that
11、the formal parameters receive the values of the argumentsTo obtain input values, we need to change the variables that are arguments to the functionRecall that we have changed the values of formal parameters in a function body, but we have not changed the arguments found in the function callCall-by-r
12、eference parameters allow us to changethe variable used in the function callArguments for call-by-reference parameters must bevariables, not numbersSlide 5- 14Call-by-Reference Examplevoid getInput(double& fVariable) using namespace std; cout “ Convert a Fahrenheit temperature” “ to Celsius.n” fVari
13、able; & symbol (ampersand) identifies fVariable as a call-by-reference parameterUsed in both declaration and definition!Slide 5- 15Display 5.4Call-By-Reference DetailsCall-by-reference works almost as if the argument variable is substituted for the formalparameter, not the arguments valueIn reality,
14、 the memory location of the argumentvariable is given to the formal parameterWhatever is done to a formal parameter in the function body, is actually done to the value at the memory location of the argument variableSlide 5- 16Display 5.5 (1)Display 5.5 (2)Call ComparisonsCall By Reference vs ValueCa
15、ll-by-referenceThe function call: f(age); void f(int& ref_par);Slide 5- 17Call-by-valueThe function call: f(age); void f(int var_par);MemoryNameLocationContents age100134 initial1002Ahours100323.51004Example: swapValuesvoid swap(int& variable1, int& variable2) int temp = variable1; variable1 = varia
16、ble2; variable2 = temp;If called with swap(firstNum, secondNum);firstNum is substituted for variable1 in the parameter listsecondNum is substituted for variable2 in the parameter listtemp is assigned the value of variable1 (firstNum) since the next line will loose the value in firstNumvariable1 (fir
17、stNum) is assigned the value in variable2 (secondNum)variable2 (secondNum) is assigned the original value of variable1 (firstNum) which was stored in tempSlide 5- 18Mixed Parameter ListsCall-by-value and call-by-reference parameters can be mixed in the same functionExample:void goodStuff(int& par1,
18、int par2, double& par3);par1 and par3 are call-by-reference formal parametersChanges in par1 and par3 change the argument variablepar2 is a call-by-value formal parameterChanges in par2 do not change the argument variableSlide 5- 19Choosing Parameter TypesHow do you decide whether a call-by-referenc
19、eor call-by-value formal parameter is needed?Does the function need to change the value of the variable used as an argument?Yes? Use a call-by-reference formal parameterNo? Use a call-by-value formal parameterSlide 5- 20Display 5.6Inadvertent Local VariablesIf a function is to change the value of a
20、variablethe corresponding formal parameter must be a call-by-reference parameter with an ampersand (&) attachedForgetting the ampersand (&) creates a call-by-value parameterThe value of the variable will not be changedThe formal parameter is a local variable that has noeffect outside the functionHar
21、d error to findit looks right!Slide 5- 21Display 5.7Section 5.2 ConclusionCan youWrite a void-function definition for a function calledzeroBoth that has two reference parameters, bothof which are variables of type int, and sets the valuesof both variables to 0.Write a function that returns a value a
22、nd has a call-by-reference parameter? Write a function with both call-by-value and call-by-reference parametersSlide 5- 225.3Using Procedural AbstractionUsing Procedural AbstractionFunctions should be designed so they can be used as black boxesTo use a function, the declaration and commentshould be
23、sufficientProgrammer should not need to know the details of the function to use itSlide 5- 24Functions Calling FunctionsA function body may contain a call to anotherfunctionThe called function declaration must still appearbefore it is calledFunctions cannot be defined in the body of another function
24、Example: void order(int& n1, int& n2) if (n1 n2) swapValues(n1, n2); swapValues called if n1 and n2 are not in ascending orderAfter the call to order, n1 and n2 are in ascending orderSlide 5- 25Display 5.8 (1)Display 5.8 (2)Pre and PostconditionsPreconditionStates what is assumed to be true when the
25、 functionis calledFunction should not be used unless the precondition holdsPostconditionDescribes the effect of the function callTells what will be true after the function is executed(when the precondition holds)If the function returns a value, that value is describedChanges to call-by-reference par
26、ameters are describedSlide 5- 26swapValues revisitedUsing preconditions and postconditions thedeclaration of swapValues es:void swapValues(int& n1, int& n2);/Precondition: variable1 and variable 2 have/ been given values/ Postcondition: The values of variable1 and/ variable2 have been / interchanged
27、Slide 5- 27Function celsiusPreconditions and postconditions make the declaration for celsius:double celsius(double farenheit);/Precondition: fahrenheit is a temperature / expressed in degrees Fahrenheit/Postcondition: Returns the equivalent temperature/ expressed in degrees CelsiusSlide 5- 28Why use
28、 preconditionsand postconditions?Preconditions and postconditions should be the first step in designing a functionspecify what a function should doAlways specify what a function should do beforedesigning how the function will do itMinimize design errors Minimize time wasted writing code that doesnt
29、match the task at handSlide 5- 29Case StudySupermarket PricingProblem definitionDetermine retail price of an item given suitable input5% markup if item should sell in a week10% markup if item expected to take more than a week5% for up to 7 days, changes to 10% at 8 daysInputThe wholesale price and t
30、he estimate of days until item sellsOutputThe retail price of the itemSlide 5- 30Supermarket Pricing:Problem AnalysisThree main subtasksInput the dataCompute the retail price of the itemOutput the resultsEach task can be implemented with a functionNotice the use of call-by-value and call-by-referenc
31、e parameters in the following function declarationsSlide 5- 31Supermarket Pricing:Function getInputvoid getInput(double& cost, int& turnover);/Precondition: User is ready to enter values / correctly./Postcondition: The value of cost has been set to/ the wholesale cost of one item./ The value of turn
32、over has been/ set to the expected number of/ days until the item is sold.Slide 5- 32Supermarket Pricing:Function pricedouble price(double cost, int turnover);/Precondition: cost is the wholesale cost of one/ item. turnover is the expected/ number of days until the item is/ sold./Postcondition: retu
33、rns the retail price of the itemSlide 5- 33Supermarket Pricing:Function giveOutputvoid giveOutput(double cost, int turnover, double price);/Precondition: cost is the wholesale cost of one item;/ turnover is the expected time until sale/ of the item; price is the retail price of / the item./Postcondi
34、tion: The values of cost, turnover, and price/ been written to the screen.Slide 5- 34Supermarket Pricing:The main functionWith the functions declared, we can write the main function: int main() double wholesaleCost, retailPrice; int shelftime; getInput(wholesaleCost, shelftime); retailPrice = price(
35、wholesaleCost, shelftime); giveOutput(wholesaleCost, shelftime, retailPrice); return 0; Slide 5- 35Supermarket Pricing:Algorithm Design - priceImplementations of getInput and giveOutputare straightforward, so we concentrate on the price functionpseudocode for the price functionIf turnover = 7 days t
36、hen return (cost + 5% of cost);else return (cost + 10% of cost);Slide 5- 36Supermarket Pricing:Constants for The price FunctionThe numeric values in the pseudocode will berepresented by constantsConst double LOW_MARKUP = 0.05; / 5%Const double HIGH_MARKUP = 0.10; / 10%Const int THRESHOLD = 7; / At 8
37、 days use /HIGH_MARKUPSlide 5- 37Supermarket Pricing:Coding The price FunctionThe body of the price function if (turnover = THRESHOLD) return ( cost + (LOW_MARKUP * cost) ) ; else return ( cost + ( HIGH_MARKUP * cost) ) ;See the complete program in Slide 5- 38Display 5.9 (1)Display 5.9 (2)Display 5.
38、9 (3)Supermarket Pricing :Program TestingTesting strategiesUse data that tests both the high and low markup casesTest boundary conditions, where the program is expectedto change behavior or make a choiceIn function price, 7 days is a boundary conditionTest for exactly 7 days as well as one day more
39、and one day lessSlide 5- 39Section 5.3 ConclusionCan youDefine a function in the body of another function?Call one function from the body of another function?Give preconditions and postconditions for the predefined function sqrt?Slide 5- 405.4Testing and DebuggingTesting and Debugging FunctionsEach
40、function should be tested as a separate unitTesting individual functions facilitates finding mistakes Driver programs allow testing of individual functionsOnce a function is tested, it can be used in the driver program to test other functionsFunction getInput is tested in the driver programof and Sl
41、ide 5- 42Display 5.10 (1)Display 5.10 (2)StubsWhen a function being tested calls other functionsthat are not yet tested, use a stubA stub is a simplified version of a functionStubs are usually provide values for testing ratherthan perform the intended calculationStubs should be so simple that you ha
42、ve confidencethey will perform correctlyFunction price is used as a stub to test the rest of the supermarket pricing program in and Slide 5- 43Display 5.11 (1)Display 5.11 (2)Rule for Testing FunctionsFundamental Rule for Testing FunctionsTest every function in a program in which every other functio
43、n in that program has already been fully tested and debugged.Slide 5- 44Section 5.4 ConclusionCan youDescribe the fundamental rule for testing functions?Describe a driver program?Write a driver program to test a function?Describe and use a stub?Write a stub?Slide 5- 455.5General Debugging Techniques
44、General Debugging TechniquesStubs, drivers, test cases as described in the previous section Keep an open mindDont assume the bug is in a particular locationDont randomly change code without understanding what you are doing until the program worksThis strategy may work for the first few small programs you write but is doomed to failure for any programs of moderate complexityShow the program to someone elseSlide 5- 47General Debugging TechniquesCheck for common errors, e.g.Local vs. Reference Parameter= instead
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年度市场调研与分析咨询服务合同范本
- 2025版新能源车辆采购合同范本6篇
- 2025年度高端电子元器件国际贸易进口合同格式
- 2025年度跨境电商物流仓储设施建设合同模板
- 2025年度数字经济股权质押融资合同
- 2025年度环保设备制造公司股权转让与市场拓展合同
- 2025年荒山土地承包经营权抵押合同示范文本
- 2025年度硅酮胶产品检测服务采购合同
- 2025年度海上货物运输合同船舶航行环境监测与保护协议
- 2025年度股权质押借款合同变更及修订标准
- 语文-百师联盟2025届高三一轮复习联考(五)试题和答案
- 地理-山东省潍坊市、临沂市2024-2025学年度2025届高三上学期期末质量检测试题和答案
- 永磁直流(汽车)电机计算程序
- 国家电网招聘2025-企业文化复习试题含答案
- 医院物业服务组织机构及人员的配备、培训管理方案
- 外观判定标准
- 江西上饶市2025届数学高二上期末检测试题含解析
- 脑卒中后吞咽障碍患者进食护理团体标准
- 工行人工智能风控
- 2023风电机组预应力混凝土塔筒与基础结构设计标准
- 2024年南京铁道职业技术学院高职单招(英语/数学/语文)笔试历年参考题库含答案解析
评论
0/150
提交评论