版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、Chapter 4Procedural Abstraction and Functions That Return a ValueOverview4.1 Top-Down Design 4.2 Predefined Functions4.3 Programmer-Defined Functions4.4 Procedural Abstraction4.5 Local Variables4.6 Overloading Function NamesSlide 4- 34.1Top-Down DesignTop Down DesignTo write a programDevelop the alg
2、orithm that the program will useTranslate the algorithm into the programminglanguage Top Down Design (also called stepwise refinement)Break the algorithm into subtasksBreak each subtask into smaller subtasksEventually the smaller subtasks are trivial to implement in the programming languageSlide 4-
3、5Benefits of Top Down DesignSubtasks, or functions in C+, make programsEasier to understandEasier to changeEasier to writeEasier to testEasier to debugEasier for teams to developSlide 4- 64.2Predefined FunctionsPredefined FunctionsC+ comes with libraries of predefined functionsExample: sqrt function
4、 theRoot = sqrt(9.0); returns, or computes, the square root of a numberThe number, 9, is called the argumenttheRoot will contain 3.0Slide 4- 8Function Callssqrt(9.0) is a function callIt invokes, or sets in action, the sqrt functionThe argument (9), can also be a variable or an expressionA function
5、call can be used like any expressionbonus = sqrt(sales) / 10;Cout “The side of a square with area “ area “ is “ sqrt(area);Slide 4- 9Display 4.1Function Call SyntaxFunction_name (Argument_List)Argument_List is a comma separated list:(Argument_1, Argument_2, , Argument_Last)Example:side = sqrt(area);
6、cout “2.5 to the power 3.0 is “ pow(2.5, 3.0); Slide 4- 10Function Libraries Predefined functions are found in librariesThe library must be “included” in a programto make the functions availableAn include directive tells the compiler which library header file to include.To include the math library c
7、ontaining sqrt(): #include Newer standard libraries, such as cmath, also requirethe directive using namespace std;Slide 4- 11Other Predefined Functionsabs(x) - int value = abs(-8);Returns absolute value of argument xReturn value is of type intArgument is of type xFound in the library cstdlibfabs(x)
8、- double value = fabs(-8.0);Returns the absolute value of argument xReturn value is of type doubleArgument is of type doubleFound in the library cmathSlide 4- 12Display 4.2Random Number GenerationReally pseudo-random numbers1. Seed the random number generator only once#include #include srand(time(0)
9、;2. The rand() function returns a random integer that is greater than or equal to 0 and less than RAND_MAXrand();Slide 4- 13Random NumbersUse % and + to scale to the number range you wantFor example to get a random number from 1-6 to simulate rolling a six-sided die:int die = (rand() % 6) + 1;Can yo
10、u simulate rolling two dice?Generating a random number x where 10 x 21?Slide 4- 14Type CastingRecall the problem with integer division:int totalCandy = 9, numberOfPeople = 4;double candyPerPerson;candyPerPerson = totalCandy / numberOfPeople; candyPerPerson = 2, not 2.25!A Type Cast produces a value
11、of one type from another typestatic_cast(totalCandy) produces a doublerepresenting the integer value of totalCandySlide 4- 15Type Cast Exampleint totalCandy = 9, numberOfPeople = 4;double candyPerPerson;candyPerPerson = static_cast(totalCandy) / numberOfPeople;candyPerPerson now is 2.25!This would a
12、lso work: candyPerPerson = totalCandy / static_cast( numberOfPeople);This would not! candyPerPerson = static_cast( totalCandy / numberOfPeople);Slide 4- 16Integer division occurs before type castOld Style Type CastC+ is an evolving languageThis older method of type casting may be discontinued in fut
13、ure versions of C+candyPerPerson = double(totalCandy)/numberOfPeople; candyPerPerson = (double) totalCandy /numberOfPeople;Slide 4- 17Section 4.2 ConclusionSlide 4- 18Can youDetermine the value of d? double d = 11 / 2;Determine the value of pow(2,3)fabs(-3.5)sqrt(pow(3,2) 7 / abs(-2)ceil(5.8)floor(5
14、.8)Convert the following to C+4.3Programmer-Defined FunctionsProgrammer-Defined FunctionsTwo components of a function definitionFunction declaration (or function prototype)Shows how the function is calledMust appear in the code before the function can be calledSyntax:Type_returned Function_Name(Para
15、meter_List); ment describing what function doesFunction definitionDescribes how the function does its taskCan appear before or after the function is calledSyntax: Type_returned Function_Name(Parameter_List) /code to make the function work Slide 4- 20;Function DeclarationTells the return typeTells th
16、e name of the functionTells how many arguments are neededTells the types of the argumentsTells the formal parameter namesFormal parameters are like placeholders for the actualarguments used when the function is calledFormal parameter names can be any valid identifierExample:double totalCost(int numb
17、erPar, double pricePar);/ Compute total cost including 5% sales tax on/ numberPar items at cost of pricePar eachSlide 4- 21Function DefinitionProvides the same information as the declaration Describes how the function does its taskExample:double totalCost(int numberPar, double pricePar) const double
18、 TAX_RATE = 0.05; /5% tax double subtotal; subtotal = pricePar * numberPar; return (subtotal + subtotal * TAX_RATE);Slide 4- 22function headerfunction bodyThe Return StatementEnds the function callReturns the value calculated by the functionSyntax: return expression; expression performs the calculat
19、ion orexpression is a variable containing the calculated valueExample: return subtotal + subtotal * TAX_RATE;Slide 4- 23The Function CallTells the name of the function to useLists the argumentsIs used in a statement where the returned valuemakes senseExample:double bill = totalCost(number, price);Sl
20、ide 4- 24Display 4.3Function Call DetailsThe values of the arguments are plugged into the formal parameters (Call-by-value mechanism with call-by-value parameters)The first argument is used for the first formal parameter, the second argument for the secondformal parameter, and so forth.The value plu
21、gged into the formal parameter is usedin all instances of the formal parameter in the function bodySlide 4- 25Display 4.4Alternate DeclarationsTwo forms for function declarationsList formal parameter namesList types of formal parmeters, but not namesFirst aids description of the function in comments
22、 Examples: double totalCost(int numberPar, double pricePar);double totalCost(int, double);Function headers must always list formal parameter names!Slide 4- 26Order of ArgumentsCompiler checks that the types of the argumentsare correct and in the correct sequence.Compiler cannot check that arguments
23、are in thecorrect logical orderExample: Given the function declaration: char grade(int received_par, int minScore_par);int received = 95, minScore = 60;cout =10) & ( rate =10) & ( rate 20) | (rate = 0);Slide 4- 31Section 4.3 ConclusionCan youWrite a function declaration and a function definitionfor
24、a function that takes three arguments, all of typeint, and that returns the sum of its three arguments?Describe the call-by-value parameter mechanism?Write a function declaration and a function definition for a function that takes one argument of type int and one argument of type double, and that re
25、turns a value of type double that is the average of the two arguments?Slide 4- 324.4Procedural AbstractionProcedural AbstractionThe Black Box AnalogyA black box refers to something that we know how to use, but the method of operation is unknownA person using a program does not need to knowhow it is
26、codedA person using a program needs to know what theprogram does, not how it does itFunctions and the Black Box AnalogyA programmer who uses a function needs to know what the function does, not how it does itA programmer needs to know what will be produced if the proper arguments are put into the bo
27、xSlide 4- 34Information HidingDesigning functions as black boxes is an example of information hidingThe function can be used without knowing howit is codedThe function body can be “hidden from view”Slide 4- 35Function Implementationsand The Black BoxDesigning with the black box in mind allows usTo c
28、hange or improve a function definition withoutforcing programmers using the function to changewhat they have doneTo know how to use a function simply by reading the function declaration and its commentSlide 4- 36Display 4.7Procedural Abstraction and C+Procedural Abstraction is writing and using func
29、tions as if they were black boxesProcedure is a general term meaning a “function like”set of instructionsAbstraction implies that when you use a function asa black box, you abstract away the details of the code in the function bodySlide 4- 37Procedural Abstraction and FunctionsWrite functions so the
30、 declaration and commentis all a programmer needs to use the functionFunction comment should tell all conditions required of arguments to the functionFunction comment should describe the returnedvalueVariables used in the function, other than the formal parameters, should be declared in the function
31、 bodySlide 4- 38Formal Parameter NamesFunctions are designed as self-contained modulesDifferent programmers may write each functionProgrammers choose meaningful names for formal parametersFormal parameter names may or may not match variable names used in the main part of the programIt does not matte
32、r if formal parameter names match other variable names in the programRemember that only the value of the argument is plugged into the formal parameterSlide 4- 39Display 4.8Case Study Buying PizzaWhat size pizza is the best buy?Which size gives the lowest cost per square inch?Pizza sizes given in dia
33、meterQuantity of pizza is based on the area whichis proportional to the square of the radiusSlide 4- 40Buying Pizza Problem DefinitionInput:Diameter of two sizes of pizzaCost of the same two sizes of pizzaOutput:Cost per square inch for each size of pizzaWhich size is the best buyBased on lowest pri
34、ce per square inchIf cost per square inch is the same, the smaller sizewill be the better buySlide 4- 41Buying Pizza Problem AnalysisSubtask 1 Get the input data for each size of pizzaSubtask 2Compute price per inch for smaller pizzaSubtask 3Compute price per inch for larger pizzaSubtask 4Determine
35、which size is the better buySubtask 5Output the resultsSlide 4- 42Buying Pizza Function AnalysisSubtask 2 and subtask 3 should be implementedas a single function becauseSubtask 2 and subtask 3 are identical tasksThe calculation for subtask 3 is the same as the calculation for subtask 2 with differen
36、t argumentsSubtask 2 and subtask 3 each return a single valueChoose an appropriate name for the functionWell use unitpriceSlide 4- 43Buying Pizza unitprice Declarationdouble unitprice(int diameter, int double price);/Returns the price per square inch of a pizza/The formal parameter named diameter is
37、 the /diameter of the pizza in inches. The formal / parameter named price is the price of the/ pizza.Slide 4- 44Buying Pizza Algorithm DesignSubtask 1Ask for the input values and store them in variablesdiameterSmalldiameterLargepriceSmallpriceLargeSubtask 4Compare cost per square inch of the two piz
38、zas usingthe less than operator Subtask 5Standard output of the resultsSlide 4- 45Buying Pizza unitprice AlgorithmSlide 4- 46Subtasks 2 and 3 are implemented as calls tofunction unitpriceunitprice algorithmCompute the radius of the pizzaComputer the area of the pizza using Return the value of (price
39、 / area)Buying Pizza unitprice PseudocodePseudocodeMixture of C+ and englishAllows us to make the algorithm more precise without worrying about the details of C+ syntaxunitprice pseudocoderadius = one half of diameter;area = * radius * radiusreturn (price / area)Slide 4- 47Buying Pizza The Calls of
40、unitpriceMain part of the program implements calls of unitprice asdouble unitPriceSmall, unitPriceLarge;unitPriceSmall = unitprice(diameterSmall, priceSmall);unitPriceLarge = unitprice(diameterLarge, priceLarge);Slide 4- 48Buying Pizza First try at unitpricedouble unitprice (int diameter, double pri
41、ce) const double PI = 3.14159; double radius, area; radius = diameter / 2; area = PI * radius * radius; return (price / area);Oops! Radius should include the fractional partSlide 4- 49Buying Pizza Second try at unitpricedouble unitprice (int diameter, double price) const double PI = 3.14159; double
42、radius, area; radius = diameter / static_cast(2) ; area = PI * radius * radius; return (price / area);Now radius will include fractional partsradius = diameter / 2.0 ; / This would also workSlide 4- 50Display 4.10 (1)Display 4.10 (2)Program TestingPrograms that compile and run can still produce erro
43、rsTesting increases confidence that the programworks correctlyRun the program with data that has known outputYou may have determined this output with pencil and paperor a calculatorRun the program on several different sets of dataYour first set of data may produce correct results inspite of a logica
44、l error in the codeRemember the integer division problem? If there is no fractional remainder, integer division will give apparently correct resultsSlide 4- 51Use PseudocodePseudocode is a mixture of English and the programming language in usePseudocode simplifies algorithm design by allowing you to
45、 ignore the specific syntax of the programming language as you work out the details of the algorithmIf the step is obvious, use C+If the step is difficult to express in C+, use English Slide 4- 52Section 4.4 ConclusionCan youDescribe the purpose of the comment that panies a function declaration?Desc
46、ribe what it means to say a programmer should be able to treat a function as a black box?Describe what it means for two functions to be black box equivalent?Slide 4- 534.5Local VariablesLocal VariablesVariables declared in a function:Are local to that function, they cannot be used from outside the f
47、unctionHave the function as their scopeVariables declared in the main part of a program:Are local to the main part of the program, they cannot be used from outside the main partHave the main part as their scopeSlide 4- 55Display 4.11 (1)Display 4.11 (2)Global ConstantsGlobal Named ConstantAvailable
48、to more than one function as well as themain part of the programDeclared outside any function bodyDeclared outside the main function body Declared before any function that uses itExample: const double PI = 3.14159; double volume(double); int main() PI is available to the main function and to functio
49、n volumeSlide 4- 56Display 4.12 (1)Display 4.12 (2)Global VariablesGlobal Variable - rarely used when morethan one function must use a common variableDeclared just like a global constant except const is not usedGenerally make programs more difficult to understand and maintainSlide 4- 57Formal Parame
50、tersare Local VariablesFormal Parameters are actually variables that arelocal to the function definitionThey are used just as if they were declared in the function bodyDo NOT re-declare the formal parameters in the function body, they are declared in the functiondeclarationThe call-by-value mechanis
51、mWhen a function is called the formal parameters are initialized to the values of thearguments in the function callSlide 4- 58Display 4.13 (1)Display 4.13 (2)Block ScopeLocal and global variables conform to the rules of Block ScopeThe code block (generally defined by the ) where an identifier like a
52、 variable is declared determines the scope of the identifierBlocks can be nestedSlide 4- 59Display 4.14Namespaces RevisitedThe start of a file is not always the best place for using namespace std;Different functions may use different namespacesPlacing using namespace std; inside the starting brace o
53、f a functionAllows the use of different namespaces in different functionsMakes the “using” directive local to the functionSlide 4- 60Display 4.15 (1)Display 4.15 (2)Example: Factorialn! Represents the factorial functionn! = 1 x 2 x 3 x x nThe C+ version of the factorial function found in Display 3.1
54、4Requires one argument of type int, nReturns a value of type intUses a local variable to store the current productDecrements n each time it does another multiplication n * n-1 * n-2 * * 1Slide 4- 61Display 4.164.6Overloading Function NamesOverloading Function NamesC+ allows more than one definition
55、for the same function nameVery convenient for situations in which the “same”function is needed for different numbers or typesof argumentsOverloading a function name means providing more than one declaration and definition using the same function nameSlide 4- 63Overloading Examplesdouble ave(double n
56、1, double n2) return (n1 + n2) / 2);double ave(double n1, double n2, double n3) return ( n1 + n2 + n3) / 3);Compiler checks the number and types of argumentsin the function call to decide which function to use cout ave( 10, 20, 30); uses the second definitionSlide 4- 64Overloading DetailsOverloaded
57、functionsMust have different numbers of formal parameters AND / OR Must have at least one different type of parameterMust return a value of the same typeSlide 4- 65Display 4.17Overloading ExampleRevising the Pizza Buying programRectangular pizzas are now offered!Change the input and add a function t
58、o compute the unit price of a rectangular pizzaThe new function could be named unitprice_rectangularOr, the new function could be a new (overloaded) version of the unitprice function that is already usedExample: double unitprice(int length, int width, double price) double area = length * width; return (price / area); Slide 4- 66Display 4.18 (1 3)Automatic Type ConversionGiven the definition double mpg(double miles, double gallons) return (miles / gallons)
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年大學(xué)文化產(chǎn)業(yè)管理(文化產(chǎn)業(yè)策劃)試題及答案
- 2025年高職(工業(yè)工程技術(shù))生產(chǎn)流程優(yōu)化試題及答案
- 2025年中職鋼琴基礎(chǔ)(幼兒音樂(lè)教學(xué))試題及答案
- 2025年中職護(hù)理學(xué)基礎(chǔ)(護(hù)理基礎(chǔ)理論)試題及答案
- 2025年中職(財(cái)經(jīng)應(yīng)用文實(shí)訓(xùn))應(yīng)用文實(shí)訓(xùn)綜合測(cè)試試題及答案
- 貴州省黔南布依族苗族自治州2025年八年級(jí)上學(xué)期期末物理試題附答案
- 中國(guó)空間站技術(shù)
- 2026年泉州市澤區(qū)臨海實(shí)驗(yàn)幼兒園招聘代課老師、保育員備考題庫(kù)及參考答案詳解一套
- 中國(guó)石化教學(xué)介紹
- 近五年甘肅中考英語(yǔ)試題及答案2025
- 四川藏區(qū)高速公路集團(tuán)有限責(zé)任公司2026年校園招聘?jìng)淇碱}庫(kù)完美版
- 多重耐藥菌醫(yī)院感染預(yù)防與控制技術(shù)指南完整版
- 2026年1月浙江省高考(首考)英語(yǔ)試題(含答案詳解)+聽(tīng)力音頻+聽(tīng)力材料
- 2026年及未來(lái)5年市場(chǎng)數(shù)據(jù)中國(guó)電能計(jì)量裝置市場(chǎng)競(jìng)爭(zhēng)格局及投資戰(zhàn)略規(guī)劃報(bào)告
- Web滲透測(cè)試與防護(hù)(虞菊花慕課版)單元設(shè)計(jì)
- 資本市場(chǎng)運(yùn)作培訓(xùn)課件
- 地理信息安全在線培訓(xùn)考試系統(tǒng)題庫(kù)及答案
- 高標(biāo)準(zhǔn)農(nóng)田監(jiān)理質(zhì)量及安全管理措施
- 供應(yīng)鏈管理工作計(jì)劃與目標(biāo)
- (正式版)JBT 9229-2024 剪叉式升降工作平臺(tái)
- GB/T 15231-2023玻璃纖維增強(qiáng)水泥性能試驗(yàn)方法
評(píng)論
0/150
提交評(píng)論