文库发布:c语言06教程_第1页
文库发布:c语言06教程_第2页
文库发布:c语言06教程_第3页
文库发布:c语言06教程_第4页
文库发布:c语言06教程_第5页
已阅读5页,还剩52页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Agenda:function(函数)VoidFunctionandvalue-returningfunctionUsingFunctionArgumentsandParametersUsingLocalVariablesinaFunctionFunctionPreconditions(前置条件)andPostconditions(后置条件)FunctionsEveryC++programmusthaveafunctioncalledmain.

Programexecutionalwaysbeginswithfunctionmain.

Anyotherfunctionsaresubprogramsthatmustbeexplicitlycalled.

WelcomePrintingAfriendofyoursisreturningfromalongtrip,andyouwanttowriteaprogramthatprintsthefollowingmessage:

**********************************************WelcomeHome!********************************************************************************************ModulesMainLevel0Print2LinesLevel1Print3LinesLevel1PrinttwolinesofasterisksPrint“WelcomeHome!”PrintfourPrint“***********************”Print“***********************”Print“***********************”Print“***********************”Print“***********************”Print“***********************”#include<stdio.h>

//程序WelcomevoidPrint2Lines();//Functionprototypes(函数原型)voidPrint4Lines();intmain(){Print2Lines();//Functioncall(函数调用)printf("WelcomeHome!\n");Print4Lines();//Functioncallreturn0;}CcodesvoidPrint2Lines()//Functionheading{printf("***************\n");printf("***************\n");}voidPrint4Lines()//Functionheading{printf("***************\n");printf("***************\n");printf("***************\n");printf("***************\n");}CcodesRevisedWelcomePrintingRevisethefunctionsothatthecallercanindicatethenumberoflinesandthenumberofasterisksperlineforprinting.Like:PrintLines(3,10);

//functioncallwillprintmessageasfollows:******************************#include<stdio.h>//程序NewWelcomevoidPrintLines(intnumLines,intnumPerLine);

//Functionprototypeintmain(){PrintLines(2,10);printf("WelcomeHome!\n");PrintLines(4,6);return0;}CcodesvoidPrintLines(intnumLines,intnumPerLine){

intcount1=1;//Loopcontrolvariableintcount2=1;

while(count1<=numLines){count2=1;

while(count2<=numPerLine)

{printf("*");count2++;

}printf(“\n”);count1++;}}CcodesRevisedWelcomePrinting(2)Revisethefunctionsothatthecallercanindicatethenumberoflinesandthenumberofasterisksperlineandthecharacterthatconsistsoftheline,forprinting.Like:PrintLines(3,10,‘#’);

//functioncallwillprintmessageasfollows:###############################include<stdio.h>//程序NewWelcome1voidPrintLines(intnumLines,intnumPerLine,charwhichChar);

intmain(){

PrintLines(2,10,'+');printf("WelcomeHome!\n");

PrintLines(4,6,'#');

return0;}CcodesvoidPrintLines(intnumLines,intnumPerLine,charwhichChar){

intcount1=1;//Loopcontrolvariableintcount2=1;

while(count1<=numLines){count2=1;

while(count2<=numPerLine)

{printf(“%c”,whichChar);count2++;

}printf(“\n”);count1++;}}CcodesFunctionCallsOnefunctioncallsanotherbyusingthenameofthecalledfunctionfollowedby()thatenclosesanargumentlist,whichmaybeempty.Afunctioncalltemporarilytransferscontrolfromthecallingfunctiontothecalledfunction.FunctionName

(ArgumentList)Theargumentlist(实参列表)isawayforfunctionstocommunicatewitheachotherbypassinginformation.Theargumentlistcancontain0,1,ormorearguments,separatedbycommas,dependingonthefunction.FunctionCallSyntaxTerminologyintmain(){

PrintLines(2,10,'+');:}voidPrintLines(…){:

printf(“%c”,whichChar);:}thecaller(callingblock)thecalledfunctionProblemWriteafunctiontocalculatethefollowing(xisaninteger):

#include<stdio.h>#include<math.h>double

f(intx);

//prototypevoidmain(){

int

x1=0;

int

x2;=9.1;

printf(“the1stresultof%dis:“,x1);

printf(“%f\n”,f(

x1

));

printf(“the2ndresultof%dis:“,x1);

printf(“%f\n”,f(

x2

));}argumentsCcodesdouble

f(

intx)

{

if(x==0)

return1.0;elsereturn1/pow(x,3)+1/pow(x,4);}TwoPartsofFunctionDefinitionbodyheadingTwoPartsofFunctionDefinitionbodyheadingintmain(){

PrintLines(2,10,'+');:}voidPrintLines(…){:

printf(“%c”,whichChar);:}bodyheadingdouble

f(

intx)

{

if(x==0)

return1.0;elsereturn1/pow(x,3)+1/pow(x,4);}Whatisinaheading?typeofvaluereturnednameoffunctionparameterlist(形参列表)voidPrintLines(intnumLines,intnumPerLine,charwhichChar

){:

cout<<whichChar;:}Whatisinaheading?typeofvaluereturnednameoffunctionparameterlistdouble

f(

intx);

voidPrintLines(intnumLines,intnumPerLine,charwhichChar);FunctionPrototype(函数原型)

Aprototypelookslikeaheadingbutmustendwithasemicolon,anditsparameterlistneedsonlytocontainthetypeofeachparameter.Thefollowing2typesareofthesameandareVALID.double

f(

int

);

voidPrintLines(

int,int,char

);SuccessfulFunctionCompilationBeforeafunctioniscalledinyourprogram,thecompilermusthavepreviouslyprocessedeitherthefunction’sprototypeorthefunction’sdefinition(headingandbody).

Why?

Forsuccessfulcompilation,thecompilerneedstheinformationcarriedbythefunctionprototypeorthefunctiondefinitionbeforethefunctioncall.Thisinformationincludes:----datatypeofthereturnedvalue----functionname----thenumberofparameters----datatypeofeachparameterFunctionCallsWhenafunctioniscalled,temporarymemoryisallocatedforitsvalueparameters,anylocalvariables,andforthefunction’snameifthereturntypeisnotvoid.

Flowofcontrolthenpassestothefirststatementinthefunction’sbody.

Thecalledfunction’sstatementsareexecuteduntila

returnstatement

(withorwithoutareturnvalue)orthe

closingbraceofthefunctionbodyisencountered.Thencontrolgoesbacktowherethefunctionwascalled.FunctionCalls:调用F函数:调用F函数:

被调用函数F某函数SummaryWhyweneedfunctions?Whatisafunctiondefinition?Whatpartsconsistofafunctiondefinition?Whatisafunctionprototype?Whyitisneededbythecompiler?Whatisafunctioncall?Whatwillhappenwhenafunctioncallismade?Asaprogrammer,youalwaysswitchbetweena“functioncreator”anda“functionuser”.Isthatright?Wherecomesthefunction?ReturnaValueorNOT?InC,avalue-returningfunctionreturnsonevalueofthetypespecifiedinitsheadingandprototype(calledthereturntype).Incontrast,avoid-functiondoesnotreturnanyvalue.ReturnaValueorNOT?void函数的调用是一条单独的语句,这是因为void函数并不会返回一个值,调用void函数是为了进行该函数的动作。返回值函数的调用一般使用在表达式中,这是因为需要使用该函数返回来的值。void函数的调用就像是一条命令;而返回值函数的调用一般是表达式的一部分。PrintLines(2,10,‘+’);

//void函数的调用是单独的语句printf(“%f\n”,f(x1));

//返回值函数的调用一般使用在表达式中ExampleWriteavoidfunctioncalledDisplayMessage(),whichyoucancallfrommain(),todescribethepollutionindexvalueitreceivesasaparameterYourcitydescribesapollutionindex lessthan35as“Pleasant”,

35through60as“Unpleasant”,

above60as“HealthHazard”voidDisplayMessage(intindex)

{

if(index<35)

printf(“Pleasant\n”);

elseif(index<=60)

printf(“Unpleasant\n”);

elseprintf(“HealthHazard\n”);}parameter

Ccodes#include<stdio.h>voidDisplayMessage(int);

//Prototypeintmain()

{

intpollutionIndex; printf(“Enterairpollutionindex:”);scanf(“%d”,&pollutionIndex);

DisplayMessage(pollutionIndex);

//Call

return0;} TheRestoftheProgram31argumentsReturnStatementreturn;

//NovaluetoreturnIsvalidonlyinthebodyblockofavoidfunction.Causescontroltoleavethefunctionandimmediatelyreturntothecallingblock,leavinganysubsequentstatementsinthefunctionbodyunexecuted.#include<stdio.h>voidDisplayMessage(int);

//Prototypeintmain() {

DisplayMessage(15);

//Functioncall

printf(“GoodBye\n“); return0;}voidDisplayMessage(intn) {printf(“Ihavelikedmathfor%dyears\n“,n);

return;

//explicitlyindicateswheretoreturn}VoidFunctionsStandAlone33intmain() {

charch;

scanf(“%c”,&ch);

DisplayMessage(ch);

//Functioncall

printf(“GoodBye\n“);

return0;}voidDisplayMessage(char

ch) {

if(ch==‘s’)

return;

//returnwhenneededelseprintf(“Thecharacteris:%c”,ch);}Sometimes…34DisplayMessagefunctionProgramwithSeveralFunctionsmainfunctionffunctionProgramwithSeveralFunctionsmainfunctionSquarefunctionCubefunctionProgramwithSeveralFunctionsmainfunction程序中函数之间的关系

函数定义即为函数。C++程序虽然由若干个函数组成,但各个函数是相互独立的,即各个函数定义是互相独立的(相互分离)。某函数的函数体中不能有另一个函数的定义。函数与函数之间的关系是:调用与被调用。除此以外,没有任何其它关系。程序中函数之间的关系intmain(){:intcube(intn){:}:} 错!程序中函数之间的关系intmain(){…cube(x

);:} intcube(intn){:}ArgumentListandParameterListAparameterlist

isthemeansusedforafunctiontoshareinformationprovidedbyargumentlistwiththeblockcontainingthecall.intmain(){

PrintLines(

2,

10

,'+‘

);}voidPrintLines(intnumLines,intnumPerLine,charwhichChar){

:}ClassifiedbyLocationArgumentsParametersAlwaysappearinafunctioncallwithinthecallingblock.Alwaysappearinthefunctionheading.SomeCbooksUsetheterm“actualparameters”forarguments.Thosebooksthenrefertoparametersas“formalparameters”43Example#include<math.h>#include<stdio.h>doublemulSqrt(int,int);intmain(){doublex;intx1=2,x2=3;

x=mulSqrt(x1,x2);

printf(“%f\n”,x);

return0;}doublemulSqrt(inta1,inta2){doublex;

x=a1*a2;

if(x<0)return-1.0;elsereturnsqrt(x);}44ArgumentListandParameterList一般情况下,实参的数量、位置与数据类型应该与形参一致。doublemulSqrt(inta1,inta2){……}mulSqrt(x1,x2)45每个实参的数据类型应该与相应位置的形参的数据类型一致,否则会引起自动类型转换。例如若mulSqrt的函数调用如下,其返回值是多少?

mulSqrt(2.1,3.4)?2.1和3.4自动转换成2和3并传递给mulSqrt函数里的形参a1和a2,从而令a1和a2的值为2和3。所以这个调用返回的值是sqrt(6)即2.44949。ArgumentListandParameterList46值形参相对应的实参可以是任何具有一个值的项目:常量、变量或表达式。例如

mulSqrt(3,4)//常量作实参

mulSqrt(x1,x2)//变量作实参

mulSqrt(x1,4)//常量、变量作实参

mulSqrt(2*3+1,x2)//表达式、变量作实参ArgumentListandParameterList47x=mulSqrt(x1,x2);实参与形参是不同的内存空间。调用时,实参值单向传递给形参变量。然后

,实参与形参就没有任何关系。

22main函数中的x1mulSqrt函数中的a1内存3main函数中的x2mulSqrt函数中的a2ArgumentListandParameterList348#include<stdio.h>voidvalPara(int);intmain(){intx=1;

valPara(x);

printf(“x=%d\n”,x);

return0;}voidvalPara(intx){x++;}运行程序屏幕将输出:

x=1ArgumentListandParameterList两个变量是否为同一变量,并不是看它们的变量名是否一样,而是看它们是否为同一个内存空间。QuestionsWhyisafunctionusedforatask? Tocutdownontheamountofdetailinyourprogram(encapsulation).Canonefunctioncallanotherfunction? Yes.Canafunctionevencallitself? Yes,thatiscalledrecursion(递归);itisveryusefulandrequiresspecialcareinwriting.AnAssertion(断言)Anassertionisatruth-valuedstatement--onethatiseithertrueorfalse(

notnecessarilyinC++code

)[即表示某种状况的语句]Examples

studentCount>0 sumisassigned&&count>0 response==‘y’or‘n’ 0.0<=deptSales<=25000.0 beta==beta@entry*2PreconditionsandPostconditionsAprecondition

isanassertiondescribingeverythingthatthefunctionrequirestobetrueatthemomentthefunctionisinvoked.

Apostcondition

describesthestateatthemomentthefunctionfinishesexecuting,providingthepreconditionistrue.Thecaller

isresponsibleforensuringtheprecondition,andthefunctioncodemustensurethepostcondition.

Forexample...Functioninterfaceandimplementation接口函数首部(声明)+前置条件:如何调用该函数后置条件+目的:该函数是用来干什么的设计函数设计接口:说明函数要实现的功能及如何调用该函数设计实现部分Functioninterfaceandimplementationvoidswap(/*inout*/int&firstInt,/*inout*/int&secondInt)//Precondition:firstIntandsecondIntareassigned//Postcondition:firstInt==secondInt@entry// &&secondInt==firstInt@entry{

::}接口实现用户关注设计者关注函数的注释(comments)清晰规范的注释,这是良好而基本

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论