




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
12Introductionto
C++Programming2OBJECTIVESInthischapteryou’lllearn:TowritesimplecomputerprogramsinC++.Towritesimpleinputandoutputstatements.Tousefundamentaltypes.Basiccomputermemoryconcepts.Tousearithmeticoperators.Theprecedenceofarithmeticoperators.Towritesimpledecision-makingstatements.32.1 Introduction2.2 FirstPrograminC++:PrintingaLineofText2.3 ModifyingOurFirstC++Program2.4 AnotherC++Program:AddingIntegers2.5 MemoryConcepts2.6 Arithmetic2.7 DecisionMaking:EqualityandRelationalOperators2.8 (Optional)SoftwareEngineeringCaseStudy:ExaminingtheATMRequirementsDocument2.9 Wrap-Up
42.1IntroductionC++programmingFacilitatesdisciplinedapproachtocomputerprogramdesignProgramsprocessinformationanddisplayresultsFiveexamplesdemonstrateHowtodisplaymessagesonthescreenHowtoobtaininformationfromtheuserHowtoperformarithmeticcalculationsHowtomakedecisionsbycomparingnumbers52.2FirstPrograminC++:PrintingaLineofTextSimpleprogramPrintsalineoftextIllustratesseveralimportantfeaturesofC++62.2FirstPrograminC++:PrintingaLineofText(Cont.)CommentsExplainprogramstoyouandotherprogrammersImproveprogramreadabilityIgnoredbycompilerSingle-linecommentBeginswith//Example//Thisisatext-printingprogram.Multi-linecommentStartswith
/*Endswith*/7Outlinefig02_01.cpp
(1of1)
fig02_01.cpp
output(1of1)
Single-linecommentsPreprocessordirectivetoincludeinput/outputstreamheaderfile<iostream>FunctionmainappearsexactlyonceineveryC++programFunctionmainreturnsanintegervalueLeftbrace{beginsfunctionbodyCorrespondingrightbrace}endsfunctionbodyStatementsendwithasemicolon;NamecoutbelongstonamespacestdStreaminsertionoperatorKeywordreturnisoneofseveralmeanstoexitafunction;value0indicatesthattheprogramterminatedsuccessfully8GoodProgrammingPractice2.1Everyprogramshouldbeginwithacommentthatdescribesthepurposeoftheprogram,author,dateandtime.(Wearenotshowingtheauthor,dateandtimeinthisbook’sprogramsbecausethisinformationwouldberedundant.)92.2FirstPrograminC++:PrintingaLineofText(Cont.)PreprocessordirectivesProcessedbypreprocessorbeforecompilingBeginwith#Example#include<iostream>Tellspreprocessortoincludetheinput/outputstreamheaderfile<iostream>WhitespaceBlanklines,spacecharactersandtabsUsedtomakeprogramseasiertoreadIgnoredbythecompiler10CommonProgrammingError2.1Forgettingtoincludethe<iostream>
headerfileinaprogramthatinputsdatafromthekey-boardoroutputsdatatothescreencausesthecompilertoissueanerrormessage,becausethecompilercannotrecognizereferencestothestreamcomponents(e.g.,cout).11GoodProgrammingPractice2.2Useblanklinesandspacecharacterstoenhanceprogramreadability.122.2FirstPrograminC++:PrintingaLineofText(Cont.)FunctionmainApartofeveryC++programExactlyonefunctioninaprogrammustbemainCanreturnavalueExampleintmain()Thismainfunctionreturnsaninteger(wholenumber)Bodyisdelimitedbybraces({})StatementsInstructtheprogramtoperformanactionAllstatementsendwithasemicolon(;)132.2FirstPrograminC++:PrintingaLineofText(Cont.)Namespacestd::Specifiesusinganamethatbelongsto“namespace”stdCanberemovedthroughtheuseofusingstatementsStandardoutputstreamobjectstd::cout“Connected”toscreenDefinedininput/outputstreamheaderfile<iostream>142.2FirstPrograminC++:PrintingaLineofText(Cont.)Streaminsertionoperator<<
Valuetoright(rightoperand)insertedintoleftoperandExamplestd::cout<<"Hello";Insertsthestring"Hello"intothestandardoutputDisplaystothescreenEscapecharactersAcharacterprecededby"\"Indicates“special”characteroutputExample"\n"Cursormovestobeginningofnextlineonthescreen15CommonProgrammingError2.2OmittingthesemicolonattheendofaC++statementisasyntaxerror.(Again,preprocessordirectivesdonotendinasemicolon.)Thesyntaxofaprogramminglanguagespecifiestherulesforcreatingaproperprograminthatlanguage.AsyntaxerroroccurswhenthecompilerencounterscodethatviolatesC++’slanguagerules(i.e.,itssyntax).Thecompilernormallyissuesanerrormessagetohelptheprogrammerlocateandfixtheincorrectcode.(cont…)16CommonProgrammingError2.2Syntaxerrorsarealsocalledcompilererrors,compile-timeerrorsorcompilationerrors,becausethecompilerdetectsthemduringthecompilationphase.Youwillbeunabletoexecuteyourprogramuntilyoucorrectallthesyntaxerrorsinit.Asyou’llsee,somecompilationerrorsarenotsyntaxerrors.172.2FirstPrograminC++:PrintingaLineofText(Cont.)returnstatementOneofseveralmeanstoexitafunctionWhenusedattheendofmainThevalue0indicatestheprogramterminatedsuccessfullyExamplereturn0;18GoodProgrammingPractice2.3Manyprogrammersmakethelastcharacterprintedbyafunctionanewline(\n).Thisensuresthatthefunctionwillleavethescreencursorpositionedatthebeginningofanewline.Conventionsofthisnatureencouragesoftwarereusability—akeygoalinsoftwaredevelopment.19Fig.2.2
|Escapesequences.20GoodProgrammingPractice2.4Indenttheentirebodyofeachfunctiononelevelwithinthebracesthatdelimitthebodyofthefunction.Thismakesaprogram’sfunctionalstructurestandoutandhelpsmaketheprogrameasiertoread.21GoodProgrammingPractice2.5Setaconventionforthesizeofindentyouprefer,thenapplyituniformly.Thetabkeymaybeusedtocreateindents,buttabstopsmayvary.Werecommendusingeither1/4-inchtabstopsor(preferably)threespacestoformalevelofindent.222.3ModifyingOurFirstC++ProgramTwoexamplesPrinttextononelineusingmultiplestatements(Fig.2.3)EachstreaminsertionresumesprintingwherethepreviousonestoppedPrinttextonseverallinesusingasinglestatement(Fig.2.4)EachnewlineescapesequencepositionsthecursortothebeginningofthenextlineTwonewlinecharactersback-to-backoutputsablankline23Outlinefig02_03.cpp
(1of1)fig02_03.cppoutput(1of1)Multiplestreaminsertionstatementsproduceonelineofoutputbecauseline8endswithoutanewline24Outlinefig02_04.cpp
(1of1)fig02_04.cppoutput
(1of1)Usenewlinecharacterstoprintonmultiplelines252.4AnotherC++Program:AddingIntegersVariableIsalocationinmemorywhereavaluecanbestoredCommondatatypes(fundamental,primitiveorbuilt-in)int–forintegernumberschar–forcharactersdouble–forfloatingpointnumbersDeclarevariableswithdatatypeandnamebeforeuseintinteger1;intinteger2;intsum;26Outlinefig02_05.cpp
(1of1)fig02_05.cppoutput(1of1)DeclareintegervariablesUsestreamextractionoperatorwithstandardinputstreamtoobtainuserinputStreammanipulatorstd::endloutputsanewline,then“flushes”outputbufferConcatenating,chainingorcascadingstreaminsertionoperations272.4AnotherC++Program:AddingIntegers(Cont.)Variables(Cont.)YoucandeclareseveralvariablesofsametypeinonedeclarationComma-separatedlistintinteger1,integer2,sum;VariablenameMustbeavalididentifierSeriesofcharacters(letters,digits,underscores)CannotbeginwithdigitCasesensitive(uppercaselettersaredifferentfromlowercaseletters)28GoodProgrammingPractice2.6Placeaspaceaftereachcomma(,)
tomakeprogramsmorereadable.29GoodProgrammingPractice2.7Someprogrammersprefertodeclareeachvariableonaseparateline.Thisformatallowsyoutoplaceadescriptivecommentnexttoeachdeclaration.30PortabilityTip2.1C++allowsidentifiersofanylength,butyourC++implementationmayimposesomerestrictionsonthelengthofidentifiers.Useidentifiersof31charactersorfewertoensureportability.31GoodProgrammingPractice2.8Choosingmeaningfulidentifiershelpsmakeaprogramself-documenting—apersoncanunderstandtheprogramsimplybyreadingitratherthanhavingtorefertomanualsorcomments.32GoodProgrammingPractice2.9Avoidusingabbreviationsinidentifiers.Thispromotesprogramreadability.33GoodProgrammingPractice2.10Avoididentifiersthatbeginwithunderscoresanddoubleunderscores,becauseC++compilersmayusenameslikethatfortheirownpurposesinternally.Thiswillpreventnamesyouchoosefrombeingconfusedwithnamesthecompilerschoose.34Error-PreventionTip2.1LanguageslikeC++are“movingtargets.”Astheyevolve,morekeywordscouldbeaddedtothelanguage.Avoidusing“l(fā)oaded”wordslike“object”asidentifiers.Eventhough“object”isnotcurrentlyakeywordinC++,itcouldbecomeone;therefore,futurecompilingwithnewcompilerscouldbreakexistingcode.35GoodProgrammingPractice2.11Alwaysplaceablanklinebetweenadeclarationandadjacentexecutablestatements.Thismakesthedeclarationsstandoutintheprogramandcontributestoprogramclarity.36GoodProgrammingPractice2.12Ifyouprefertoplacedeclarationsatthebeginningofafunction,separatethemfromtheexecutablestatementsinthatfunctionwithoneblanklinetohighlightwherethedeclarationsendandtheexecutablestatementsbegin.372.4AnotherC++Program:AddingIntegers(Cont.)Inputstreamobjectstd::cinfrom<iostream>UsuallyconnectedtokeyboardStreamextractionoperator>>Waitsforusertoinputvalue,pressEnter(Return)keyStoresavalueinthevariabletotherightoftheoperatorConvertsthevaluetothevariable’sdatatypeExamplestd::cin>>number1;ReadsanintegertypedatthekeyboardStorestheintegerinvariablenumber1382.4AnotherC++Program:AddingIntegers(Cont.)Assignmentoperator=AssignsthevalueontherighttothevariableontheleftBinaryoperator(twooperands)Example:sum=variable1+variable2;Addsthevaluesofvariable1andvariable2StorestheresultinthevariablesumStreammanipulatorstd::endlOutputsanewlineFlushestheoutputbuffer39GoodProgrammingPractice2.13Placespacesoneithersideofabinaryoperator.Thismakestheoperatorstandoutandmakestheprogrammorereadable.402.4AnotherC++Program:AddingIntegers(Cont.)ConcatenatingstreaminsertionoperationsUsemultiplestreaminsertionoperatorsinasinglestatementStreaminsertionoperationknowshowtooutputeachtypeofdataAlsocalledchainingorcascadingExamplestd::cout<<"Sumis"<<number1+number2
<<std::endl;Outputs"Sumis“Thenoutputsthesumofvariablesnumber1andnumber2Thenoutputsanewlineandflushestheoutputbuffer412.5MemoryConceptsVariablenamesCorrespondtoactuallocationsinthecomputer'smemoryEveryvariablehasaname,atype,asizeandavalueWhenanewvalueplacedintoavariable,thenewvalueoverwritestheoldvalueWritingtomemoryis“destructive”ReadingvariablesfrommemoryisnondestructiveExamplesum=number1+number2;Althoughthevalueofsum
is
overwrittenThevaluesofnumber1andnumber2
remainintact42Fig.2.6
|Memorylocationshowingthenameandvalueofvariablenumber1.43Fig.2.7
|Memorylocationsafterstoringvaluesfornumber1andnumber2.44Fig.2.8
|Memorylocationsaftercalculatingandstoringthesumofnumber1andnumber2.452.6ArithmeticArithmeticoperators*
Multiplication/
DivisionIntegerdivisiontruncates(discards)theremainder7/5evaluatesto1%Themodulusoperatorreturnstheremainder7%5evaluatesto246CommonProgrammingError2.3Attemptingtousethemodulusoperator(%)withnonintegeroperandsisacompilationerror.472.6Arithmetic(Cont.)Straight-lineformRequiredforarithmeticexpressionsinC++Allconstants,variablesandoperatorsappearinastraightlineGroupingsubexpressionsParenthesesareusedinC++expressionstogroupsubexpressionsInthesamemannerasinalgebraicexpressionsExamplea*(b+c)Multipleatimesthequantityb+c48Fig.2.9
|Arithmeticoperators.492.6Arithmetic(Cont.)RulesofoperatorprecedenceOperatorsinparenthesesareevaluatedfirstFornested(embedded)parenthesesOperatorsininnermostpairareevaluatedfirstMultiplication,divisionandmodulusareappliednextOperatorsareappliedfromlefttorightAdditionandsubtractionareappliedlastOperatorsareappliedfromlefttoright50Fig.2.10
|Precedenceofarithmeticoperators.51CommonProgrammingError2.4Someprogramminglanguagesuseoperators**or^
torepresentexponentiation.C++doesnotsupporttheseexponentiationoperators;usingthemforexponentiationresultsinerrors.52GoodProgrammingPractice2.14Usingredundantparenthesesincomplexarithmeticexpressionscanmaketheexpressionsclearer.53Fig.2.11
|Orderinwhichasecond-degreepolynomialisevaluated.542.7DecisionMaking:EqualityandRelationalOperatorsConditionExpressioncanbeeithertrueorfalseCanbeformedusingequalityorrelationaloperatorsifstatementIftheconditionistrue,thebodyoftheifstatementexecutesIftheconditionisfalse,thebodyoftheifstatementdoesnotexecute55Fig.2.12
|Equalityandrelationaloperators.56CommonProgrammingError2.5Asyntaxerrorwilloccurifanyoftheoperators==,!=,>=and<=
appearswithspacesbetweenitspairofsymbols.57CommonProgrammingError2.6Reversingtheorderofthepairofsymbolsinanyoftheoperators!=,>=and<=(bywritingthemas=!,=>
and=<,respectively)isnormallyasyntaxerror.Insomecases,writing!=
as=!
willnotbeasyntaxerror,butalmostcertainlywillbealogicerrorthathasaneffectatexecutiontime.(cont…)58CommonProgrammingError2.6YouwillunderstandwhywhenyoulearnaboutlogicaloperatorsinChapter
5.Afatallogicerrorcausesaprogramtofailandterminateprematurely.Anonfatallogicerrorallowsaprogramtocontinueexecuting,butusuallyproducesincorrectresults.
59CommonProgrammingError2.7Confusingtheequalityoperator==
withtheassignmentoperator=
resultsinlogicerrors.Theequalityoperatorshouldberead“isequalto,”andtheassignmentoperatorshouldberead“gets”or“getsthevalueof”or“isassignedthevalueof.”Somepeopleprefertoreadtheequalityoperatoras“doubleequals.”AswediscussinSection
5.9,confusingtheseoperatorsmaynotnecessarilycauseaneasy-to-recognizesyntaxerror,butmaycauseextremelysubtlelogicerrors.
60Outlinefig02_13.cpp
(1of2)usingdeclarationseliminatetheneedforstd::prefixYoucanwritecoutandcinwithoutstd::prefixDeclaringvariablesifstatementcomparesthevaluesofnumber1andnumber2totestforequalityIftheconditionistrue(i.e.,thevaluesareequal),executethisstatementifstatementcomparesvaluesofnumber1andnumber2totestforinequalityIftheconditionistrue(i.e.,thevaluesarenotequal),executethisstatementComparestwonumbersusingrelationaloperators<and>61Outlinefig02_13.cpp
(2of2)fig02_13.cppoutput(1of3)(2of3)(3of3)Comparestwonumbersusingtherelationaloperators<=and>=62GoodProgrammingPractice2.15Placeusingdeclarationsimmediatelyafterthe#includetowhichtheyrefer.63GoodProgrammingPractice2.16Indentthestatement(s)inthebodyofanifstatementtoenhancereadability.64GoodProgrammingPractice2.17Forreadability,thereshouldbenomorethanonestatementperlineinaprogram.65CommonProgrammingError2.8Placingasemicolonimmediatelyaftertherightparenthesisaftertheconditioninanifstatementisoftenalogicerror(althoughnotasyntaxerror).Thesemicoloncausesthebodyoftheifstatementtobeempty,sotheifstatementperformsnoaction,regardlessofwhetherornotitsconditionistrue.Worseyet,theoriginalbodystatementoftheifstatementnowwouldbecomeastatementinsequencewiththeifstatementandwouldalwaysexecute,oftencausingtheprogramtoproduceincorrectresults.66CommonProgrammingError2.9Itisasyntaxerrortosplitanidentifierbyinsertingwhite-spacecharacters(e.g.,writingmainasmain).67GoodProgrammingPractice2.18Alengthystatementmaybespreadoverseverallines.Ifasinglestatementmustbesplitacrosslines,choosemeaningfulbreakingpoints,suchasafteracommainacomma-separatedlist,orafteranoperatorinalengthyexpression.Ifastatementissplitacrosstwoormorelines,indentallsubsequentlinesandleft-alignthegroupofindented.68Fig.2.14
|Precedenceandassociativityoftheoperatorsdiscussedsofar.69GoodProgrammingPractice2.19Refertotheoperatorprecedenceandassociativitychartwhenwritingexpressionscontainingmanyoperators.Confirmthattheoperatorsintheexpressionareperformedintheorderyouexpect.Ifyouareuncertainabouttheorderofevaluationinacomplexexpression,breaktheexpressionintosmallerstatementsoruseparenthesestoforcetheorderofevaluation,exactlyasyouwoulddoinanalgebraicexpression.Besuretoobservethatsomeoperatorssuchasassignment(=)associaterighttoleftratherthanlefttoright.702.8
溫馨提示
- 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)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年郵輪旅游市場發(fā)展現(xiàn)狀與未來趨勢深度分析報告
- 2025年P(guān)MP項目管理專業(yè)人士資格考試模擬試卷:項目合同管理要點解析
- 商業(yè)合同上訴狀樣板
- 聲學(xué)產(chǎn)品項目分析報告
- 有關(guān)荒山承包合同范文(15篇)
- 2025年提花彩條線毯項目投資可行性研究分析報告
- 印制品行業(yè)深度研究分析報告(2024-2030版)
- 2025年萬用電表恒溫烙鐵行業(yè)深度研究分析報告
- 五金吧椅項目投資可行性研究分析報告(2024-2030版)
- 2025年白炭黑濕法混煉橡膠市場分析報告
- 有限空間作業(yè)氣體檢測記錄表
- 2024至2030年中國汽車鋁輪轂行業(yè)市場現(xiàn)狀調(diào)研與發(fā)展趨勢分析報告
- 八年級語文上冊 第一單元 第3課《鄉(xiāng)愁 余光中》教案 冀教版
- 2024中考英語必考1600詞匯分類速記表
- 江蘇泰州市泰興經(jīng)濟開發(fā)區(qū)國有企業(yè)招聘筆試題庫2024
- 2024年風(fēng)力發(fā)電運維值班員(技師)技能鑒定考試題庫-下(判斷題)
- DL∕T 1709.3-2017 智能電網(wǎng)調(diào)度控制系統(tǒng)技術(shù)規(guī)范 第3部分:基礎(chǔ)平臺
- 考核辦法和考核方案
- 化妝品生產(chǎn)OEM合同書
- 海上CANTITRAVEL平臺樁基施工關(guān)鍵技術(shù)應(yīng)用v7
- 有色金屬冶金概論課程教案
評論
0/150
提交評論