課程資源軟件構(gòu)造6語句keynote_第1頁
課程資源軟件構(gòu)造6語句keynote_第2頁
課程資源軟件構(gòu)造6語句keynote_第3頁
課程資源軟件構(gòu)造6語句keynote_第4頁
課程資源軟件構(gòu)造6語句keynote_第5頁
已閱讀5頁,還剩124頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡介

E學(xué)???指 ??對指 doubleintegrate(double(*f)(doublex),doublelb,doubleub); structeth_header{unsignedchardst[6];unsignedcharsrc[6];

NOPAIN,NO Nothing?? !unsignedsNOPAIN,NO Nothing?? !}; structeth_header*header (structeth_header*)printf("SRC:%02X-%02X-%02X-%02X-%02X-header->src[0],header->src[1],header->src[2],header->src[3],header->src[4],header->src[5]);??內(nèi)存中的位置:0x0001EA40?內(nèi)存 616263646162630061626364616263006162636461626300chara[7]6162636461626300???????C++?insertNode->next=currentNode->next;insertNode->previous= if(currentNode->next!=currentNode->next->previous=}currentNode->next=?與NULL或nullptr如:if(NULLp),if insertNode->next= insertNode->previous= if(currentNode->next!=currentNode->next->previous }currentNode->next= Node*followingNode=startNode->next;newMiddkeNode->next= newMiddkeNode->previous= if(followingNode!=NULL){followingNode>previous=}startNode->next=?inta=1;int*p=&a;float*p1=??void指針又名萬能指針,在現(xiàn)在的很多程序中,當(dāng)參數(shù)不確定時就?萬能指針代替,這?類的指針程/進(jìn)程函數(shù)??char*buffer=(char*)malloc(i+1)??記得delete ??最好delete,注意數(shù)組需要delete[]????Assert(NULL!=pointer,ttemptingtodeletenulldeletepointer;pointer=NULL;??????起來和?般的C++?重載了 ??C++’S?類auto_ptr是C??慢慢被C++11中的其他 ?auto_ptr對象掌管指針,當(dāng)auto_ptr對象被刪除或者離開了作? ?#include<iostream>//forstd::cout,std::endl#include<memory>//forstd::auto_ptr#include<stdlib.h>//forEXIT_SUCCESSvoidLeaky(){int*x=newint(5);//heapallocated(*x)++;std::cout<< *x<< std::endl;}voidNotLeaky(){std::auto_ptrx(newint(5));//wrapped,heap-allocated(*x)++;std::cout<< *x<< std::endl;}intmain(intargc,char**argv){returnEXIT_SUCCESS;C++’SAUTO_PTR的使??#include<memory>//forstd::auto_ptr#include<stdlib.h>//forEXIT_SUCCESSusingnamespacestd;typedefstruct{inta,b;}intmain(intargc,char**argv)auto_ptr<int>x(newint(5));//Constructsan auto_ptrobjecteitherfromapointerorfromanother auto_*ptr x.get();//Returnsapointertotheobjectpointed auto_ptrintval=*x;//Returnsareferencetothevaluepointedby auto_ptrauto_ptr<IntPair>ip(newIntPair);ip->a=100;x.reset(newint(1));//Resettheauto_ptrwithanewheap-allocatedobject.ptr=x.release();//Releaseresponsibilityforingthepointed-toobject.deleteptr;return?有效地安排和組織語句是提?代碼的質(zhì)量、正確性、可讀性和 ????????if-?if-then-?switch-???先寫正常代碼路徑??把正常情況的處理放在if后??不要放在else???即>=和<=的邊界值誤差(off-by-?讓if?檢查???OpenFile(inputFile,statusIf(status=Status_Error)ThenerrorType=FileOpenError

<--ReadFile(inputFile,fileData,status) <--2If(status=Status_Success)ThenSummarizeFileData(fileData,summaryData,statusIf(status=Status_Error)errorType=ErrorType_DataSummaryError <--4PrintSummary(summaryData <--ErrorNormalNormalErrorErrorNormalNormalErrorNormalErrorNormal

<-- <--7EndIfEndIfEndIf

<--OpenFile(inputFile,statusIf(status=Status_Error)ThenIf(status=Status_Success)ThenIf(status=Status_Error)ThenIf(status=Status_Error)ThenEndIfEndIfEndIf

?????正常的路徑?致地 ?所有的錯誤情況都寫在后?,即elseOpenFile(inputFile,statusIf(status=Status_Success)ThenReadFile(inputFile,fileData,status)If(status=Status_Success)Then

<--SummarizeFileData(fileData,summaryData,status)If(status=Status_Success)ThenPrintSummary(summaryData) <--3SaveSummaryData(summaryData,status)If(status=Status_Success)Then <--4

<--EndIfEndIf

<--NominalNominalNominalNominalNominalNominalErrorErrorErrorErrorEndIf

<--<--OpenFile(inputFile,statusIf(status=Status_Success)ThenIf(status=Status_Success)ThenIf(status=Status_Success)ThenSaveSummaryData(summaryData,status)If(status=Status_Success)ThenEndIfEndIfEndIf

???即>=和<=的邊界值誤差(off-by-?讓if?檢查??將復(fù)雜的判斷從代碼 ?inputCharacter<inputCharacter<SPACEelseifinputCharacter==''||inputCharacter==','||inputCharacter=='.'||inputCharacter=='!'||inputCharacter=='('||inputCharacter==')'||inputCharacter==':'||inputCharacter==';'||inputCharacter=='?'||inputCharacter=='-'

{characterType=)characterType=}elseif('0'<=inputCharacter&&inputCharacter<='9')characterType=}elseif('a'<=inputCharacter&&inputCharacter<='z')||('A'<=inputCharacter&&inputCharacter<='Z'))characterType= ?if(IsControl(inputCharacter))characterType=}elseif(IsPunctuation(inputCharacter)){}elseif(IsDigit(inputCharacter)){}elseif(IsLetter(inputCharacter)){}??些語?的編譯器會先計(jì)算布爾表達(dá)式中的每個項(xiàng)的值,然后??些語?的編譯器采?“短路(short-circuit)”或者“?短路求值(short-circuitevaluation)也叫做最?求值或者惰性最?化計(jì)算使得 a等于boola if(a&&myfunc(b)){}

?falseANDq?論q是什么總是得?如果整個表達(dá)式都被求值,你就會在循環(huán)的最后?次送代中遇whilewhile(i…MAX_ELEMENTSanditem[i]<0?由于變量i等于MAX_ELEMENTS,所以表達(dá)式item[i])就等于item[MAX_ELEMENTS],?這是?個數(shù)組下標(biāo)?if(if((denominator!= 0)&&((item/denominator)>MIN_VALUE))...?如果在denominator等于0的時候求整個表達(dá)式的值,那么?由于僅當(dāng)?shù)?部分為真的時候才去求第?個部分的值,因此當(dāng)denominator等于0的時候第?部分就不會參與計(jì)算了,??過 ??能夠理解超過3層的if ??轉(zhuǎn)換成if-then-?轉(zhuǎn)換成case? ?使?對象和多態(tài)派分polymorphicdispatch ?通過重復(fù)檢測條件中的某?部分來簡化嵌套的if?并?多重嵌套if語句就?定需要簡化,簡化的原則是能否清晰的?注:有效利?強(qiáng)調(diào)主要路徑的?法也可以使多重嵌套語句易于 //lotsofif(inputStatus==//lotsofif(printerRoutine!=NULL)//lotsofif(SetupPage())//lotsofif(AllocMem(&printData))//lotsof

這?的//lotsofcode指的是較}}}}inputStatus==inputStatus==InputStatus_Success//lotsofif(printerRoutine!=NULL)//lotsof}}

{必須要使??個更復(fù)雜的if((inputStatus==InputStatus_Success)(printerRoutine!=NULL)&&SetupPage())//lotsofif(AllocMem(&printData))//lotsof}} ?把嵌套的if結(jié)構(gòu)轉(zhuǎn)換成?組if-then-else??并?邏輯判斷本?設(shè)計(jì)的不好,?是代碼反映該邏輯判?多重if嵌套轉(zhuǎn)換為?組if-then-else語句,并不是對邏輯判斷的if(10 ty)if(100 ty)if(1000< ty){discount=0.10;}else

tydiscount=}

ty}elsediscount=

ty}}elsediscount= }過if(1000<ty過}elseif(100< ty){discount=0.05;}elseif(10< ty){discount=0.025;}elsediscount=

ifif(1000ty)discount=}elseif((100<discount=0.05;}elseif((10<discount=0.025;ty)&&ty<=1000))ty)&&ty<=100))}elseif ty<=10)discount=} E ?如 ???把if-then-elsewhile plete())//readtransactiontransaction //processtransactiondependingontypeoftransactionif(transaction.Type==TransactionType_Deposit){//processaif(transaction.AccountType==AccountType_Checking)if(transaction.AccountSubType==AccountSubType_BusinessMakeBusinessCheckDep(transaction.AccountNum,transaction.Amount);elseif(transaction.AccountSubType==AccountSubType_ al) alCheckDep(transaction.AccountNum,transaction.Amount);elseif(transaction.AccountSubType==AccountSubType_School)MakeSchoolCheckDep(transaction.AccountNum,transaction.Amount);}elseif(transaction.AccountType==AccountType_SavingsMakeSavingsDep(transaction.AccountNum,transaction.Amount);elseif(transaction.AccountType==AccountType_DebitCard)MakeDebitCardDep(transaction.AccountNum,transaction.Amount);elseif(transaction.AccountType==AccountType_MoneyMarket)MakeMoneyMarketDep(transaction.AccountNum,transaction.Amount);elseif(transaction.AccountType==elseif(transaction.AccountType==AccountType_Cd)MakeCDDep(transaction.AccountNum,transaction.Amount);}elseif(transaction.Type==TransactionType_Withdrawal)//processaif(transaction.AccountType==AccountType_Checking)MakeCheckingWithdrawal(transaction.AccountNum,transaction.Amount);elseif(transaction.AccountType==AccountType_Savings)MakeSavingsWithdrawal(transaction.AccountNum,transaction.Amount);}elseif(transaction.Type==TransactionType_Transfer){); else//processunknownkindof}}C++casewhile plete())transaction=ReadTransaction();switch(transaction.Type){case(TransactionType_Deposit):case(TransactionType_Withdrawal):case(TransactionType_Transfer):LogTransactionError("UnknownTransactionType",);}} ?使??向?qū)ο蟮募夹g(shù)來簡化該代碼的?法是使?不同的類來封?在此基礎(chǔ)上可以考慮使?多態(tài)或接?的技術(shù),即構(gòu)造相應(yīng)的類while plete())transaction=ReadTransaction();switch(transaction.Type){case(TransactionType_Deposit):

class Complete(): Complete():case( Complete():case(TransactionType_TransferLogTransactionError("UnknownTransactionType",transaction);

Complete(): Complete():}? 轉(zhuǎn)換成if-then-else ?? LoopEnd(program,?{if(LoopEnd(AProgram,input))infiniteloop}?循環(huán)指的是任意?種迭代控制結(jié)構(gòu)(i tivecontrol??C和Java中的for、while和do- VisualBasic中的For-Next、While-Wend?計(jì)數(shù)循環(huán)(countedloop)??連續(xù)求值的循環(huán)(continuouslyevaluatedloop?預(yù)先并不知道將要執(zhí)?多少次,它會在每次迭代時檢查??限循環(huán)(endless??迭代器循環(huán)( tor?????????如果是在循環(huán)的中間檢查,那么位于檢查前?的那?部分循環(huán)就?帶退出的循環(huán)(Loop-with-exit)就是終?條件出現(xiàn)在循環(huán)中間??VisualBasic明確?持loop-with-exit?在C、C和Java中可以?結(jié)構(gòu)化的while和break來模擬它,或者在其他語?中?goto來模擬它(someexit(someexitcondition)ThenExit??如果把循環(huán)條件檢測放在循環(huán)開始或結(jié)束處,那就需要?所謂半循環(huán)的代碼就是為了完成整個循環(huán)?設(shè)置在循環(huán)score=GetNextRating(&ratingIncrement);rating=rating+ratingIncrement;

while((score<targetScore)&&(ratingIncrement!=0)){GetNextScore(&scoreIncrement);score=score+scoreIncrement;GetNextRating(&ratingIncrement);rating=rating+ratingIncrement;} score=0; while(true){GetNextRating(&ratingIncrement);rating=rating+ratingIncrement;if(!((score<targetScore)&&(ratingIncrement!=0)){}GetNextScore(&scoreIncrement);score=score+scoreIncrement;}

??多個退出條件分散在不同位置,會使得某些終?條件在??帶退出的循環(huán)是單?單出的結(jié)構(gòu)化控制結(jié)構(gòu),也是?種?選的?????????不正確的循環(huán)下 ?… while(!inputFile.EndOfFile()&&moreDataAvailable)}?????goto????while(true)?C、Java、VisualBasic??for(;;)?在適當(dāng)?shù)那闆r下多使?for?for循環(huán)的優(yōu)點(diǎn)是把循環(huán)的控制代碼集中在?處,從?有?注意:當(dāng)循環(huán)的控制部分較為復(fù)雜的時候,for循環(huán)未必?在while循環(huán)更適?的時候,不要使?for?當(dāng)循環(huán)的控制部分較為復(fù)雜的時候,可以考慮使?while//readalltherecordsfromafor(inputFile.MoveToStart(),recordCount=recordCount++){}recordCount=for(inputFile.GetRecord()){}

//readalltherecordsfromarecordCount=0;while(!inputFile.EndOfFile())

}

???while((inputChar=dataFile.GetChar())!=CharType_Eof);}doinputChar=}while(inputChar!=CharType_Eof??循環(huán)內(nèi)務(wù)操作 ??像i=i+1或者j??????????循環(huán)下標(biāo)的最終取值根據(jù)語?以及實(shí)現(xiàn)的不同?具有微妙差???for(recordCount=0;recordCount<MAX_RECORDS;recordCount++){if(entry[recordCount]==testValue){}}lotsof ifif(recordCount<MAX_RECORDS){return(true);}elsereturn(false}found=found=for(recordCount=0;recordCount<MAX_RECORDS;recordCount++){if(entry[recordCount]==testValue){found=}}

//lotsofreturn(foundStructuredProgrammingEdsgerDijkstra在1969年NATO順序“順序選擇迭代 決策點(diǎn)(decisionpoint)策點(diǎn)(decisionpoint)”數(shù)量來衡量復(fù)雜度if、whiIe、repeat、for、and、or:給case語句中的每?種情況都加if(((status==Success)&&done)||(!done&&(numLines>=maxLines)))0-6-??????程序可以通過return和exit這類控制結(jié)構(gòu),在任何需要的時候退?ComparisonComparisonCompare(intvalue1,intvalue2){if(value1<value2){return}elseif(value1>value2)return}return}N??防衛(wèi)?句(guardclause)(早返回或早退出)來簡化復(fù)雜的錯?如果代碼中必須要在執(zhí)?正常操作之前做?量的錯誤條Iffile.validName()ThenIffile.Open()ThenIfencryptionKey.valid()Iffile.Decrypt(encryptionKey)Then'lotsofcodeEndIfEndIfEndEnd

VisualBasicVisualBasic'setup,bailingoutiferrorsareIfNotfile.validName()ThenExitSubIfNotfile.Open()ThenExitSubIfNotencryptionKey.valid()ThenExitIfNotfile.Decrypt(encryptionKey)ThenExit'lotsof…VisualBasic示例:更實(shí)際地利用防 IfNotfile.validName()errorStatus=FileError_InvalidFileNameExitSubEndIfNotfile.Open()errorStatus=FileError_CantOpenFileExitSubEndIfNotencryptionKey.valid()errorStatus=FileError_InvalidEncryptionKeyExitSubEndIfNotfile.Decrypt(encryptionKey)ThenerrorStatus=FileError_CantDecryptFileExitSubEnd???個?程序??負(fù)責(zé)解決某個問題的??部分,它還把?當(dāng)問題的?部分很容易解決,?問題的?部分也很容易???通常這意味著該?程序中含有?項(xiàng)判斷,?須進(jìn)?步遞???該安全計(jì)數(shù)器必須是?個不隨每次?程序調(diào)??重新創(chuàng)If(If(safetyCounter>SAFETY_LIMIT)ExitSubEndIfVisualVisualBasic示例:用安全計(jì)數(shù)?PublicSubRecursiveProc(ByRefsafetyCounterAsIntegersafetyCounter=safetyCounter+RecursiveProc(safetyCounter)EndSub?循環(huán)遞歸形如A調(diào)?BB調(diào)?C,C調(diào)???????longfact(intn){if(n==0)return1;elsereturnn*fact(n-1);}

longfact(intn){ints=1for(inti=1;i<=n;i++s=s*i;?sreturn}intf(intn){if(n==1||n==2)return1;elsereturnf(n-1)+f(n-2);}

intf(intn){ints=1,s1=1,s2=1for(inti=3;i<=n;++i{s=s1+s2s2s1保存f(n-2)的值s1s;//保存f(n-1)的值}return}?GOTO是?種?條件跳轉(zhuǎn)???C、C、Java、VB甚?Ada都(部分)?持???Dijkstra寫了?封信,結(jié)論是“GOTO是有害的?EdsgerW.Dijkstra,GoToStatementHarmful,CommunicationsoftheACM.Vol.11,No.3,March1968.?該?中:?個程序的易讀性和易理解性同其中所包 ?EdsgerW.Dijkstra(1930.5~2002.8)??以最 ?1960年8?,Dijkstra?1962年參加THE?1972年與Hoare(80年 ?含有g(shù)oto?使?goto?使?goto?DonaldKnuth(1974).StructuredProgrammingwithgotoStatements.ComputingSurveys6(4):261–301. ?DonaldKnuth/ (1938.1~)??99年的《 并列為20世紀(jì)最有影響的12部科學(xué)專著?TEX排版軟件和METAFONT??74?75年當(dāng) ?77年請姚奇志(2000年 ?????部分論斷 SubPurgeFiles(ByReferrorStateAsError_Code…While(fileIndex<numFilesToPurge)fileIndex=fileIndex+1IfNot(FindFile(fileList(fileIndex),fileToPurge))errorState=FileStatus_FileFindErrorGoToEND_PROCEndIfNotOpenFile(fileToPurge)ThenerrorState=FileStatus_FileOpenErrorGoToEND_PROCEndEndSub

?嵌套的if ?嵌套的if SubPurgeFiles(ByReferrorStateAsError_CodeWhile(fileIndex<numFilesToPurgeAnderrorState=FileStatus_Success)fileIndex=fileIndex+1IfFindFile(fileList(fileIndex),fileToPurge)ThenIfOpenFile(fileToPurge)ThenIfOverwriteFile(fileToPurge)ThenIfNotErase(fileToPurge)ThenerrorState=FileStatus_FileEraseErrorEndIfElse'couldn'toverwriteEndIfElse'couldn'topenerrorState=FileStatus_FileOpenErrorEndIfElse'couldn'tfinderrorState=FileStatus_FileFindErrorEndIfEndSub

Visual SubPurgeFiles(ByReferrorStateAsError_Code…While(fileIndex<numFilesToPurge)And(errorState=FileStatus_Success)fileIndex=fileIndex+1IfNotFindFile(fileList(fileIndex),fileToPurge)ThenerrorState=FileStatus_FileFindErrorEndIf(errorState=FileStatus_Success)ThenIfNotOpenFile(fileToPurge)ThenerrorState=FileStatus_FileOpenErrorEndIfEndIf(errorState=FileStatus_Success)ThenIfNotOverwriteFile(fileToPurge)ThenEndIfEndEndSub

VisualBasic示例:利用try-finally消除gotoSub…MakePurgeFileList(fileList,numFilesToPurgefileIndex=While(fileIndex<numFilesToPurge)fileIndex=fileIndex+1FindFile(fileList(fileIndex),fileToPurge)OpenFile(fileToPurge)Erase(fileToPurge)EndTryEnd

try-finally?表驅(qū)動法是?種編程模式?從表??查找信息?不使?邏輯語句(if和?表驅(qū) ?表驅(qū)動法的另?個好處是可以將復(fù)雜邏輯從代碼中獨(dú)?出來,if((('a'<=inputChar)&&(inputChar<='z'))||(('A'<=inputChar)&&(inputChar<='Z'))){charType=CharacterType.Letter;}elseif((inputChar=='')||(inputChar==',')(inputChar=='.')||(inputChar=='!')||(inputChar=='(')||(inputChar==')')||(inputChar==':')||(inputChar==';')||(inputChar=='?')||(inputChar=='-')){charType=}elseif'0'inputChar&&inputChar'9' charType chartype=charTypeTable[inputChar ????直 (Direct?索 ?階 (Stair-step If(If(month=1)Thendays=31ElseIf(month=2)Thendays=28ElseIf(month=3)Thendays=31…ElseIf(month=11)Thendays=30ElseIf(month=12)Thendays=31EndIfDimDimdaysPerMonth()AsInteger={31,28,31,30,31,30,31,31,31,30,31days=daysPerMonth(month-1 ?通常該?件中會 ?約500條消息,?每份?件中會存有?約20種不同的消息。這些消息源?于?些浮標(biāo)(Buoy),提供有關(guān)?溫、浮標(biāo)位置等信息。?每?條消息都有若?字段,并且每條消息都有?個消息頭,其中有?個ID,告訴你該消息屬于這20多種消息中?

?ID,以及根據(jù)該ID調(diào)?20?如果你有20種消息,那么就要有20?每次有任何?種消息的格式變了,你就不得不修改負(fù)責(zé)WhilemoremessagestoreadReadamessageheaderDecodethemessageIDfromthemessageIfthemessageheaderistype1thenPrintatype1messageElseifthemessageheaderistype2Printatype2Elseifthemessageheaderistype19thenPrintatype19messageElseifthemessageheaderistype20Printatype20WhilemoremessagestoreadReadamessageheaderDecodethemessageIDfromthemessageheaderIfthemessageheaderistype1thenInstantiateatype1messageobjectElseifthemessageheaderistype2thenInstantiateatype2messageElseifthemessageheaderistype19thenInstantiateatype19messageobjectElseifthemessageheaderistype20thenInstantiateatype20messageobjectEndifEndWhilePrint"BuoyTemperatureMessage“Readafloating-pointvaluePrint"AveragePrintthefloating-pointReadafloating-pointvaluePrint"TemperatureRange"Printthefloating-pointReadanintegervaluePrint"NumberofSamples"PrinttheintegervalueReadacharacterstringPrint"Location"PrintthecharacterReadatimeofdayPrintPrintthetimeofday?消息閱讀?程序由?個循環(huán)組成,該循環(huán)負(fù)責(zé)讀?每?個消息頭,對其ID,在Message數(shù)組中查詢其消息描述,然后每?只需要?? enumFieldType{FieldType_Last=MessageBeginNumFields5Messa

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論