3.1.8基本函數(shù)程序設(shè)計(jì) - 基本函數(shù)程序設(shè)計(jì)3.1_第1頁(yè)
3.1.8基本函數(shù)程序設(shè)計(jì) - 基本函數(shù)程序設(shè)計(jì)3.1_第2頁(yè)
3.1.8基本函數(shù)程序設(shè)計(jì) - 基本函數(shù)程序設(shè)計(jì)3.1_第3頁(yè)
3.1.8基本函數(shù)程序設(shè)計(jì) - 基本函數(shù)程序設(shè)計(jì)3.1_第4頁(yè)
3.1.8基本函數(shù)程序設(shè)計(jì) - 基本函數(shù)程序設(shè)計(jì)3.1_第5頁(yè)
已閱讀5頁(yè),還剩14頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

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. 本站所有資源如無(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ì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論