3.1.8基本函数程序设计 - 基本函数程序设计3.1_第1页
3.1.8基本函数程序设计 - 基本函数程序设计3.1_第2页
3.1.8基本函数程序设计 - 基本函数程序设计3.1_第3页
3.1.8基本函数程序设计 - 基本函数程序设计3.1_第4页
3.1.8基本函数程序设计 - 基本函数程序设计3.1_第5页
已阅读5页,还剩14页未读 继续免费阅读

下载本文档

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

文档简介

Chapter4.FunctionandProgramStruction4.1BasicsofFunctionsFormoffunctiondefinition:

return-typefunction-name(argumentdeclaration) { declarationsandstatements } aminimalfunction:dummy(){} returnstatement: returnexpression: or return(expression):4.1BasicofFunctionsExample: #include<stdio.h> #defineMAXLINE1000/*maximuminputlinelength*/ intgetline(charline[],intmax); intstrindex(charsource[],charsearchfor[]); charpattern[]=“ould”;/*patterntosearchfor*/ /*findalllinesmatchingpattern*/ main() {charline[MAXLINE]; intfound=0; while(getline(line,MAXLINE)>0) if(strindex(line,pattern)>=0){ printf(“%s”,line); found++; } returnfound; }4.1BasicofFunctions/*getline:getlineintos,returnlength*/int

getline(chars[],int

lim){intc,i; i=0; while(--lim>0&&(c=getchar())!=EOF&&c!=‘\n’)

s[i++]=c; if(c==‘\n’)s[i++]=c;

s[i]=‘\0’; returni;}/*strindex:returnindexoftins,-1ifnone*/int

strindex(chars[],chart[]){ inti,j,k;

for(i=0;s[i]!=‘\0’;i++){

for(j=i,k=0;t[k]!=‘\0’&&s[j]==t[k];j++,k++); if(k>0&&t[k]==‘\0’)return; } return-1;}4.2FunctionsReturningNon-integersmustdeclarethetypeofvalueitreturnsthecallingroutinemustknowthatreturnsanon-intvalue.example:

#include<ctype.h> /*atof:convertstringstodouble*/ doubleatof(chars[]) { doubleatof(chars[]) inti,sign; for(i=0;isspace(s[i]);i++);/*skipwhitespace*/ sign=(s[i]==‘-’)?-1:1; if(s[i]==‘+’||s[i]==‘-’)i++;for(val=0.0;isdigit(s[i]);i++) val=10.0*val+(s[i]-’0’);if(s[i]==‘.’)i++; for(power=1.0;isdigit(s[i]);i++){ val=10.0*val+(s[i]-’0’); power*=10.0; } returnsign*val/power;

}4.2FunctionsReturningNon-integerscallingatof():declaration(functionprotype) #include<stdio.h> #defineMAXLINE100 main() { doublesum,atof(char[]); charline[MAXLINE];

intgetline(charline[],intmax); sum=0; while(getline(line,MAXLINE)>0) printf(“\t%g\n”,sum+=atof(line)); return0; }callingor:atof();inoldversion4.3ExternalVariablesexternalvariables:definedoutsideofanyfunctionandavailabletomanyfunctions(globallyaccessiable)Example: calculatorthatprovidestheoperators+,-,*/ usereversePolish(逆波兰)notationinsteadofinfix(中缀). 12-45+*<====>(1-2)*(4+5) themainalgorithmoftheprogram: while(nextoperatororoperandisnotend_of_fileindicator) if(number)

pushit elseif(operator)

popoperands dooperation

pushresult elseif(newline)

popandprinttopofstack elseerror4.3ExternalVariables#include<stdio.h>#include<math.h>#defineMAXOP100/*maxsizeofoperandoroperator*/intgetop(char[]);voidpush(double); /*reversePolishcalculator*/main(){ inttype; doubleop2; chars[MAXOP];

4.3ExternalVariableswhile((type=getop(s))!=EOF){ switch(type){ caseNUMBER:push(atof(s));break; case‘+’:push(pop()+pop());break; case‘*’:push(pop()*pop());

case‘-’:op2=pop();push(pop()-op2);break; case‘/’:op2=pop(); if(op2!=0.0)push(pop()/op2); elseprintf(“error:zerodivisor\n”);break; case‘\n’:printf(“\t.8g\n”,pop());break; default:printf(“erroe:unknowncommand%s\n”,s);break;} } return0;} 4.3ExternalVariables#defineMAXVAL100/*maximumdepthofvalstack*/intsp=0;/*nextfreestackposition*/doubleval[MAXVAL];/*valstack*//*push:pushfontovaluestack*/voidpush(doublef){ if(sp<MAXVAL)val[sp++]=f;elseprintf(‘error:stackfull,can’tpush%g\n”,f);}/*pop:popandreturntopvaluefromstack*/doublepop(void){ if(sp>0)returnval[--sp]; else{printf(“error:stackempty\n”); return0.0; }}4.3ExternalVariables#include<ctype.h>intgetch(void);voidungetch(int);/*getop:getnextoperatorornumericoperand*/intgetop(chars[]){inti,c;while((s[0]=c=getch())==‘‘||c==‘\t’);s[1]=‘\0’;if(!isdigit(c)&&c!=‘.’)returnc;i=0;if(isdigit(c))while(isdigit(s[++i}=c=getch()));if(c==‘.’)while(isdigit(s[++i]=getch()));

s[i]=‘\0’;if(c!=EOF)ungetch(c);returnNUMBER;}4.3ExternalVariables#defineBUFSIZE100charbuf[BUFSIZE];/*bufferforungetch*/intbufp=0;/*nextfreepositioninbuf*/intgetch(void)/*getacharacter*/{ return(bufp>0)?buf[--bufp]:getchar();}voidungetch(intc)/*pushcharacterbackoninput*/{if(bufp>=BUFSIZE)printf(“ungetch:toomanycharacters\n”); elsebufp[bufp++]=c;}Getint与getstr:getch与ungetch的作用#include<stdio.h>charbuf[10];intbp=-1;chargetch(){

if(bp>=0)returnbuf[bp--];elsereturngetchar();}voidungetch(charc){

buf[++bp]=c;}intgetint(){intn=0;charc;while((c=getch())!=EOF){ if(c>='0'&&c<='9')n=n*10+c-'0'; else{ungetch(c);break;}}returnn;}char*getstr(chars[]){inti=0;charc;while((c=getch())!=EOF&&c!='\n'){ if(c>=‘0’&&c<=‘9’)

{ungetch(c);break;} elses[i++]=c;}s[i]='\0';returns;}main(){

inti,j;

chars[20];

i=getint();

getstr(s);

j=getint();

printf("%d%s%d\n",i,s,j);}4.4ScopeRulesscopeofaname(variable,function,ect);

thepartoftheprogramwithinwhichthenamecanbeused.scopeofanautomaticvariable:thefunctioninwhichthenameisdeclaredscopeofanexternalvariableorafunction:

fromthepointatwhichitisdeclaredtotheednofthefileifanexternalvariableistobereferredtobeforeitisdefind oranameisdefindinadifferentsourcefile: anexterndeclarationismandatoryInfile1: Infile2:

externintsp;externdoubleval[];voidpush(doublef){…}voidpop(void){…}intsp=0;doubleval[MAXVAL];4.5HeaderFilesplacethedefinitionsanddeclarationssharedamongthefilesinaheaderfile.example:

calc.h:

#defineNUMBER‘0’voidpush(double);intgetop(char[]);intgetch(void);voidungetch(int);#include<stdio.h>#include<math.h>#include“calc.h”#defineMAXOP100main(){…}#include<stdio.h>#include<ctype.h>#include“calc.h”getop(){…} stack.c:…getch.c…main.c:getop.c:4.6StaticVariablesstatic:(1)appliedtoanexternalvariablesorfunction: limitsthescopeofthatobjecttotherestofthesourcefile,thenameisinvisiableoutsidethefile. staticchar[BUFSIZE];/*bufferforungetch*/intgetch(void){…} voidungetch(intc){…} (2)appliedtoaninternalvariable:

thescopeisthefunction(asautomaticvariable,butitremaininexistenceastheprogram(notthefunction)isactivated.

voidExample(){staticinti=1;printf(“%dtimes\n”,i++);}main(){Example();Example();Example();} result:1times2times3timesstaticvariablesisinitializedonlythefirsttimefunctionisentered4.7RegisterVariablesregister:advisesthecompliertoplacethevariableinregisters,inordertoresultinsmallerandfasterprograms.format registerintx; registercharc;

example: f(registerunsignedm,registerlongn) {registerinti; … }

notice:registerdeclarationcanonlybeappliedtoautomaticvariableandtotheformalparametersofafunctiononlyafewvariablescanbekeptinregisters,excessdeclarationwillbeignored.cannottaketheaddressofaregistervariabletherearerestrictionsontypesofregistervariables.4.8BlockStructureblock:{……}variablecanbedeclaredinablock(followtheleftbrace),,thescopeofthevariableistheblock,andremaininexistenceuntilmatchingtherightbrace.

if(n>0){

inti;/*declareanewi*/for(i=0;i<n;i++)….} thescopeof“i”thevariableininnerscopewillhidevariablesinouterscopeofthesamename.intx,y;f(doublex){doubley;…x=y+1;…}g()…innerfirst4.9Initializationintheabsenceofexplicitinitialization:externalandstaticvariableareinitializedtozeroautomaticandregistervariableshaveundefinedinitialvalueinexplicitinitialization:

温馨提示

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

评论

0/150

提交评论